Saturday, March 11, 2017

Using Notepad++ for writing Ruby Programs

Let us first configure Notepad++ for editing Ruby programs.
From the Notepad++ menu, click on Settings => Preferences. Click on Language Menu/Tab settings. Under the tab settings for [Default] modify the tab size and Replace by space options as shown below. We set the tab size to 2 and we set Replace by space option to use spaces instead of tab character.
Setting editor properties in Notepad++ for Ruby
Now we will add a custom menu in the Run menu for running Ruby programs. This way you can run Ruby programs directly from the Notepad++ editor. From the Notepad++ menu, click on Run => Run. This opens up the following window.
Configuring a shortcut for running Ruby programs in Notepad++
In the text field, enter the following command. In order for this to work, you need to have Ruby 1.9.x installed and the Ruby bin folder must be on the PATH environment variable. See this tutorial for step by step instructions on installing Ruby in Windows.
cmd /K ruby "$(FULL_CURRENT_PATH)"
Click on the Save… button to save this as a custom command.
Configuring a shortcut for running Ruby programs in Notepad++
Enter a name for the shortcut (Run Ruby Program) and then select a keyboard shortcut for running the command (F6). Click on OK.
Now from the Notepad++ menu, Click on Run. You will see the additional "Run Ruby Program" menu as shown below.
Custom Run Ruby option in Notepad++
In order for this shortcut to work, you need to ensure that your Ruby program is saved in a file. To test Notepad++, type in the following program,
1def fact(n)
2  if n==1
3    1
4  else
5    n * fact(n-1)
6  end
7end
8puts fact(5)
Save the file as factorial.rb. Now press F6 key or select the "Run Ruby Program" submenu from the Run menu. You should see the output of the Ruby program in a command window as shown below,

Monday, March 6, 2017

Rails 5 - has_secure_password

has_secure_password(options = {})
Adds methods to set and authenticate against a BCrypt password. This mechanism requires you to have a password_digest attribute.
The following validations are added automatically:
  • Password must be present on creation
  • Password length should be less than or equal to 72 characters
  • Confirmation of password (using a password_confirmation attribute)
If password confirmation validation is not needed, simply leave out the value for password_confirmation (i.e. don't provide a form field for it). When this attribute has a nilvalue, the  validation will not be triggered.
For further customizability, it is possible to suppress the default validations by passing validations: false as an argument.
Add bcrypt (~> 3.1.7) to Gemfile to use has_secure_password:
gem 'bcrypt', '~> 3.1.7'
Example using Active Record (which automatically includes ActiveModel::SecurePassword):
# Schema: User(name:string, password_digest:string)
class User < ActiveRecord::Base
  has_secure_password
end

user = User.new(name: 'david', password: '', password_confirmation: 'nomatch')
user.save                                                       # => false, password required
user.password = 'mUc3m00RsqyRe'
user.save                                                       # => false, confirmation doesn't match
user.password_confirmation = 'mUc3m00RsqyRe'
user.save                                                       # => true
user.authenticate('notright')                                   # => false
user.authenticate('mUc3m00RsqyRe')                              # => user
User.find_by(name: 'david').try(:authenticate, 'notright')      # => false
User.find_by(name: 'david').try(:authenticate, 'mUc3m00RsqyRe') # => user
More at http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html
https://rubyplus.com/episodes/311-Authentication-from-Scratch-in-Rails-5
https://rubyplus.com/articles/4171-Authentication-from-Scratch-in-Rails-5

Saturday, February 25, 2017

Ruby Strings Concatenation

Ruby deals with strings as well as numerical data. A string may be double-quoted ("...") or single-quoted ('...').
ruby> "abc"
   "abc"
ruby> 'abc'
   "abc"
Double- and single-quoting have different effects in some cases. A double-quoted string allows character escapes by a leading backslash, and the evaluation of embedded expressions using #{}. A single-quoted string does not do this interpreting; what you see is what you get. Examples:
ruby> puts "a\nb\nc"
a
b
c
   nil
ruby> puts 'a\nb\n'
a\nb\nc
   nil
ruby> "\n"
   "\n"
ruby> '\n'
   "\\n"
ruby> "\001"
   "\001"
ruby> '\001'
   "\\001"
ruby> "abcd #{5*3} efg"
   "abcd 15 efg"
ruby> var = " abc "
   " abc "
ruby> "1234#{var}5678"
   "1234 abc 5678"
Ruby's string handling is smarter and more intuitive than C's. For instance, you can concatenate strings with +, and repeat a string many times with *:
ruby> "foo" + "bar"
   "foobar"
ruby> "foo" * 2
   "foofoo"

More at http://www.rubyist.net/~slagell/ruby/strings.html

Finding by SQL


If you’d like to use your own SQL to find records in a table you can use find_by_sql. The find_by_sql method will return an array of objects even the underlying query returns just a single record. For example you could run this query:
Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
find_by_sql provides you with a simple way of making custom calls to the database and retrieving instantiated objects.

More at http://guides.rubyonrails.org/v2.3.11/active_record_querying.html

Finder Methods by Field

Dynamic Finders

For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called name on your Client model for example, you get find_by_name and find_all_by_name for free from Active Record. If you have also have a locked field on the Client model, you also get find_by_locked and find_all_by_locked.
You can do find_last_by_* methods too which will find the last record matching your argument.
You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an ActiveRecord::RecordNotFound error if they do not return any records, like Client.find_by_name!("Ryan")
If you want to find both by name and locked, you can chain these finders together by simply typing and between the fields for example Client.find_by_name_and_locked("Ryan", true).
There’s another set of dynamic finders that let you find or create/initialize objects if they aren’t found. These work in a similar fashion to the other finders and can be used like find_or_create_by_name(params[:name]). Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for Client.find_or_create_by_name("Ryan"):
SELECT * FROM clients WHERE (clients.name = 'Ryan') LIMIT 1 BEGIN INSERT INTO clients (name, updated_at, created_at, orders_count, locked) VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', 0, '0') COMMIT
find_or_create’s sibling, find_or_initialize, will find an object and if it does not exist will act similar to calling new with the arguments you passed in. For example:
client = Client.find_or_initialize_by_name('Ryan')
will either assign an existing client object with the name “Ryan” to the client local variable, or initialize a new object similar to calling Client.new(:name => 'Ryan'). From here, you can modify other fields in client by calling the attribute setters on it: client.locked = true and when you want to write it to the database just call save on it.

Thursday, February 23, 2017

Using Record_Select with Active_Scaffold


1. Install Paginator

C:\prj4rails\rnd>gem install paginator
Fetching: paginator-1.2.0.gem (100%)
Successfully installed paginator-1.2.0
Parsing documentation for paginator-1.2.0
Installing ri documentation for paginator-1.2.0
Done installing documentation for paginator after 2 seconds
1 gem installed

INSTALL
  1. Download from GitHub and unzip into vendor/plugins. (Rails 5 : Add Gem "record_select" in gem file)
  2. Enable and configure it on a controller.
  3. class UsersController < ApplicationController
    record_select :per_page => 5, :search_on => 'username'
end 1. Optional: to use RecordSelect RESTfully, add the following to your routes.rb: map.resources :model_id, :collection => {:browse => :get}, :member => {:select => :post} 1. Now go ahead and use it somewhere.

HOWTO

Let's assume that you have two models, NewsArticles and Authors, and every NewsArticle belongs_to :author. 
Let's assume that your goal is to set up the scaffold for NewsArticles so that the create/update forms use RecordSelect to pick the appropriate Author. To accomplish this using the default intelligence of these two plugins, you need to do two things:
  1. Configure RecordSelect on the AuthorsController.
  2. Configure the NewsArticles scaffold with config.columns[:author].form_ui = :record_select.
  3. If you want to use both RESTfully, combine the configuration in your routes.rb: map.resources :news, :active_scaffold => true, :collection => {:browse => :get}, :member => {:select => :post}
It's important to understand that the relationship between the two models is mirrored between the two controllers. The NewsArticlesController will display a form that calls RecordSelect via /authors/browse. If you want to customize which authors are returned in the result set (e.g. change the number of authors per-page), you need to configure RecordSelect on the AuthorsController.

Advice from Sergio Cambra

1. You are reading a really old web, recordselect is not in google code anymore, 
but README in github is not updated either 

Do not change your layout, don't add record_select_includes, it doesn't exist 
anymore because current way is adding //= require record_select to asset 
manifest. 
Anyway, you don't have to add anything else to your application 
manifest, ActiveScaffold already includes record_select to assets through 
record_select bridge when recordselect gem is installed. 
Q2. ActionView::Template::Error (No route matches {:*action=>"browse"*,

A2
Add record_select_routes to your resources routes:

resources :rootcauses do
record_select_routes
concerns :active_scaffold
end

It will define get browse route on collection

Q3. But its shows as Root Cause:FEATURE, how can I make as FEATURE ?

A3
It uses to_label method in your model, as ActiveScaffold, you can change to_label method in your model. Or setup recordselect to use different method or partial:


Here is some old doc, still applies:

In summary, you can use partials, and set partial name with :label option:

record_select ..., :label => 'partial name'

Or use a proc or lambda:

Welcome to Rails.. Rails... Rails !

In 1995, I started the popular Clipper...Clipper... Clipper website (no blogs then) which was very popular and linked by virtually every Clipper-related site. When I switched to Windows via Delphi in 1997, I started the Delphi... Delphi... Delphi site. In June 2007, I discovered Ruby on Rails and no prize for guessing what I am gonna name this blog. which I started on 2nd October 2007.

As at 10th June 2010, we have 13,364 unique visitors from more than 84 countries such as Angola, Andorra, Argentina, Australia, Austria, Algeria,Barbados, Bosnia and Herzogovina, Belgium, Brazil, Bulgaria, Bangladesh, Belarus, Bolivia, Chile, Cambodia, Cape Vede, Canada, China, Colombia, Costa Rica, Croatia, Cyprus, Czech Republic, Denmark, Egypt, Estonia, Finland, France, Guadeloupe, Guatemala, Germany, Greece, Hong Kong, Hungary, India, Indonesia, Ireland, Israel, Italy, Japan, Kenya, Korea, Lithuania, Latvia, Malaysia, Mexico, Macao, Netherlands, Nepal, Norway, New Zealand, Oman, Panama, Peru, Poland, Portugal,Paraguay , Philippines, Romania, Russian Federation, Saudi Arabia, Singapore, Spain, Slovakia, Slovenia, Serbia, South Korea, Slovenia, South Africa, Spain, Switzerland, Sri Lanka, Sweden, Taiwan, Thailand, Turkey, United Arab Emirates, Ukraine, USA, UK, Venezuela, Vietnam

CCH
10th June 2010, 19:42