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:

Sunday, February 19, 2017

Solving Slow Load Time

It turns out the delay was being caused by config.assets.debug = true inside of development.rb. Setting this to false resolves the problem.

By default, caching is only enabled in your production environment. To play around with caching locally you'll want to enable caching in your local environment by setting config.action_controller.perform_caching to true in the relevant config/environments/*.rb file:
config.action_controller.perform_caching = true
Changing the value of config.action_controller.perform_caching will only have an effect on the caching provided by the Action Controller component. For instance, it will not impact low-level caching, that we address below.
More at http://guides.rubyonrails.org/caching_with_rails.html

Saturday, February 11, 2017

Rails Best Practice


Migrations

Adding Columns
Rake Tasks
Remove column, Rename Table,Dropt Table, Change Column



About Routing

RESTFul Routes 
Custom Routes
Named Routes
How to Redirect
Root Route
Route Parameters - Part 1
Route Parameters Part 2
Route Parameters Part 3

About Rails Controllers

tweet=find(1) cluttering up show.html.erb
Notice the tweets... tweets...tweets
Keep model code such as tweet=Tweet.find(1) in controllers

Instance variables via @ allows views to see what is in the controller
How to use status.html.erb in Show method via render
Using param[:id] in find method for flexibility

xml ? json?
Basic Controller Actions
Authorisation
Notice for Layouts
DRY out...Use before_filter





Thursday, February 9, 2017

About Rails Views





link_to helper



See also http://api.rubyonrails.org/
More RESTful Routes like

link_to "Profile", profile_path(@profile)
# => <a href="/profiles/1">Profile</a>

or the even pithier
link_to "Profile", @profile
# => <a href="/profiles/1">Profile</a>
REST stands for Representational State Transfer. (It is sometimes spelled "ReST".) It relies on a stateless, client-server, cacheable communications protocol -- and in virtually all cases, the HTTP protocol is used.
REST is an architecture style for designing networked applications. The idea is that, rather than using complex mechanisms such as CORBA, RPC or SOAP to connect between machines, simple HTTP is used to make calls between machines.
  • In many ways, the World Wide Web itself, based on HTTP, can be viewed as a REST-based architecture.
RESTful applications use HTTP requests to post data (create and/or update), read data (e.g., make queries), and delete data. Thus, REST uses HTTP for all four CRUD (Create/Read/Update/Delete) operation
Index.html.erb - List
Tweet.all in Rails 5 can be written as @Tweet.each do |tweet|





Rails Model: Validations and Relationships

Q. What is a model ?
A. Model is how Rails communicate with a data store.










VALIDATIONS











Wednesday, February 8, 2017

Try Ruby Tutorial

A really cool thing about Ruby is that you can always convert between different types using Ruby's "to" methods.
  • to_s converts values to strings.
  • to_i converts values to integers (numbers.)
  • to_a converts values to arrays.
Strings have .reverse property eg "Chee".reverse => "eejC"

ARRAYS

Arrays are basically list of stored information.

Create empty array
[]

[517, 66, 07].max => 517

Assign array to a variable

nric=>[517, 66, 07]

Sort an Array

nric.sort =>[07,66,517]
nric=>[517, 66, 07]

// ! permanently sort 
nric.sort! =>[07,66,517]
nric =>[07,66,517]

Query Array

nric.include? 67 =>false
nric.include? 07 =>true

Comple list of string methods

Hash
Hashes store related information by giving reusable labels to pieces of data.

Create Hash aka Dictionary.
books={}

or

ratings=Hash.new(0)

Stuffing an Array

books["Inferno"] = :splendid
books["Kublai Khan"] = :historical
books["Davinci Code"]=:exciting

books => {"Inferno"=>:splendid, "Kublai Khan=>:historical, "Davinci Code"=>:exciting}


Block


Basically, a block is a chuck of ruby code


RoR Zombies Tutorial : Notable point

1. Reading Value out of a Hash
This is a Hash
t={id:, status: "Delicious Brains", zombie:"Jim"}
Read Recipe
Variable[:key] => value
Example
t[:id]=3
t[:status]="Delicious Brains"
t[zombie]="Jim"

How to retrieve the tweet object with id=3
ANSWER: t=Tweet.find(3)
{id: 3, status: "Delicious Brains", zombie:"Jim"}

Nb. Use id: in Hash and :id when reading Hash value

Hash Syntax vs Dot Syntax



puts t[:status] same as puts t.status
puts t[:zombie] same as puts t.zombie

Nb. Dot Syntax more suitable to access Tables

Accessing Tables


CRUD



CREATE





READ






 UPDATE





DELETE



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