We are pleases to announce Ruby Raven which is an iOS app that will keep you updated about latest happening in Ruby Conferences world.
Inside Ruby Raven App you can see all upcoming Ruby Conferences.
People like notifications and Ruby Raven fullfills this need. Ruby Raven send notifications which keeps you updated.
This App will send the a Raven when
A new conference is announced.
A conference is opening doors for proposals so you know when to submit.
Closing dates are nearby to submit a proposal.
Registrations are open.
We like open source as other people do.
We have kept Ruby Raven open source.
Ruby Raven has two components
Server App part to keep track of latest Conferences.
iOS App which lives in your devices and is built using Swift.
You are most welcome to contribute.
This is very intial version for Ruby Raven. We are planning to add more features like showing CFP details within App, Confernce location. There are many cannot list all of them right now.
We would like to give special thank to Karan Arora for suggesting and giving feedback on Logo design and overall app feedback.
We would like to thanks all beta tester for initial feedback. We will be looking for more beta tester for future versions. Add yourself here.
We would like to thank thenounproject.com for icons.
Thanks,
]]>Listed are some feature are going introduced in version of Rails 4.2. You can also try them while it’s beta.
But apart from these there are more features which are going to ship in Rails 4.2.
Few of them are..
required
option for singular associations (belongs_to
and has_one
)Sometime we need to validate presence of associated object not the foreign key used to map the association
Lets say for each user there must be a account so we validate it like this –:
1 2 3 4 |
|
But in Rails 4.2 we just need to set required
option to true which will validate associated object is present
1 2 3 4 |
|
required
option in generator for model and migrationWhen we generate model we can pass required
option for references/associations
1
|
|
It will automatically set required
true for commentable
association
1 2 3 |
|
And in migration set null: false
for commentable
association which is basically a database validation
1 2 3 4 5 6 7 8 9 |
|
We can also pass it with polymorphic
option if we need polymorphic relation
1
|
|
This required
option can also be passed in generating migration
1
|
|
It runs all validations and returns true
if no error found otherwise return false
.
It is alias of valid?
method.
It runs all validations and returns true
if no error found otherwise
raise ActiveRecord::RecordInvalid
if any validation fails
with_options
without explicit receiverIn with_options
block we have to pass explicit receiver whether it is required or not
1 2 3 4 5 6 |
|
Now in Rails 4.2 we don’t need to pass explicit receiver to with_options
until it is required
1 2 3 4 5 6 |
|
Before Rails 4.2 we can just pass one attribute in touch
method
1 2 3 |
|
But in Rails 4.2 we can update multiple attributes at once with touch
method
1 2 |
|
Rails 4.2 added support for citext
column type in PostgreSQL adapter.
But we have to enable extension before running migration because its additional supplied module
1
|
|
citext
column type provides a case-insensitive character string type.
For example we have a users
table with bio column as citext
type
We have a user object with bio value as ‘developer’ but we search with ‘Developer’ it will return our user object in result
1 2 3 |
|
Internally citext
calls lower when comparing values so we don’t need to explicitly convert value in lowercase
1
|
|
Rails provides us few database related rake tasks such as to create/drop database and to run migrations.
There is a new rake task added rake db:purge
to empty database for current environment.
It removes your data and tables from database and of course we can pass environment RAILS_ENV
like any other rake task.
We always need some set of commands to bootstrap our application.
Now in Rails 4.2 there is default bin/setup
script where we can have all tasks to setup our application in quick and consistent way. It is located in bin directory.
There are some defaults commands given by Rails but we can add more as per our requirement.
To modify Hash values call transform_values
it accepts a block and apply the block operation to each value of hash
1 2 |
|
There is also a bang version transform_values!
which change original hash
1 2 3 |
|
There is new method truncate_words
which truncate a string by given number of words length
1
|
|
Now in Rails console/logs we can print ActiveRecord object output nicely
just pass that object to pp
method
1 2 3 4 5 6 7 8 9 10 |
|
We can skip default gems to Gem file while creating new app with --skip-gems
option. They will not be added to our Gemfile
1
|
|
Here are some more articles about rails 4.2
Thanks to all Rails contributors for making Rails awesome :)
If you any feedback on this article let me know @raysrashnmi on Twitter
]]>Few many times we require routes to behave differently and also want to do some routing based on specific conditions.
For example
Constraint routes for http methods( put, post )
Want to show different home page for different users.
Want to restrict URL for some sub domain or range of IP addresses
We can easily constraints our routes in Rails
You can filter any parameter based on Regular expression
Lets say we have route
1
|
|
If we want to restrict it for certain range of IP addresses we can do like
1
|
|
OR
1 2 3 |
|
Another example of filtering id
parameter
1
|
|
Now URL with id
as integer only allowed to hit maps#show
action
Can restrict format
parameter
1
|
|
It will generate route only for json
format so if somebody try to open HTML format for this URL it won’t hit maps show action.
We can also constraint routes on request object
1
|
|
Now URL admin.example.com/admin
will redirect to show
action of admin
controller
matches?
methodWe can constraint route dynamically based on some specific criteria by creating a matches?
method
Lets say we have to filter sub domain of URL
1 2 3 4 5 6 7 8 9 |
|
What we are doing here is checking for URL if it start with sub domain foobar
then only hit proxy#index
action. Your class must have mathes?
method either class method or instance method. If you want to make it a instance method then do
1 2 3 |
|
lambdas
Instead of writing class we can also use lambdas
1
|
|
Resource
]]>*args
as an argument in method definition it means we can pass
multiple parameters.
See the below example
1 2 3 4 5 6 7 8 |
|
But what if we just have asterisk(splat operator) as an argument?
I was looking Rails code base and found asterisk(*)
in an class initialize method.
Link: https://github.com/rails/rails/blob/master/railties/lib/rails/commands/server.rb#L42
Let’s take an example –:
1 2 3 4 5 |
|
How many arguments you passed it wont generate any error
Let’s take another example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
But now if we pass *
as an argument in child class initialize method see what
happens.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
You can see passing * as an argument help to send parameters for parent class even though child class doesn’t require those arguments
Note: *
is called splat operator in Ruby.
See some sample Rails code which is using *
https://github.com/rails/rails/blob/v4.0.0/railties/lib/rails/commands/server.rb#L40 https://github.com/rack/rack/blob/1.5.2/lib/rack/server.rb#L178
It was new to me so thought to share with you guys. I hope you can get it if you do not know about this already.
]]>val()
method and attr(‘value’)
I never faced this problem before. I thought to share this with you guys.
I had an text field
1
|
|
I had to send the value of this text field to server side
So if I do
1
|
|
Result is “New York”
1
|
|
It gives the the value entered in text field and if nothing then the placeholder value
It means val()
gives the actual value that is there in text field. $(obj).attre(‘value’)
it actually give the value of attribute ‘value’
Its is better to use val()
method to get the value of input field
Read about val()
method and attr
Rails 4 is released. Lots of new features has been added to rails. Here we will see what new directories have been added.
We will create a sample app in rails 4 so that it will be easy to see the new structure. I am assuming you have updated your rails. To check current version of rails run following command:
1
|
|
It should be Rails 4.0.0
Now create a very simple rails application
1
|
|
It creates a our app directory . You will see there are some new directories and files. Lets go to each one by one
In this directory there is new concerns/ dir under controllers/ and models/. Concerns are added to manage your models/controllers in a better way .
Mixins and modules code can be put under this dir. Lets say in our blog application we have user model and post model and we require to add comments for both model so we created a commentable module in our concerns/ dir and included in both model.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Now suppose we need to add one more module noteable to our model post.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
But we can also include Commentable to Noteable.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Because of line “extend ActiveSupport::Concern ” both Commentable and Noteable are accessible for Post class.
Its easy to cross sharing of code among models and to make your model clean.
App executables bundle, rails and rake are under this dir. So dont need to run ‘bundle exec’ before any rails command. Binstubs can also be generated using bundle command ,bundle 1.3 added spports for generating binstubs. What Binstubs are executables required to prepare the environment before original executable.
When we do
1
|
|
an executable file is genearted in gems//cucumber-1.3.2/bin dir(i am using rvm here)
1
|
|
Now we can generate using bundle command
1
|
|
It wil genrate executable in bin/. Having executables within your app ensures that they are using app ruby and gems.
We use config.filter_parameters in config/application.rb to filter out parameters which we dont want to show in log files. But Its moved to filter_parameter_logging.rb under initializers dir
Lets say we have an attribute customer_id of customer model and we want to filter in our log files then just write
1
|
|
After restarting your server if there is any request having customer_id parameter. it will not show the value of customer_id
Doc has been removed from rails directory. Its is extracted in sdoc gem and added to Gemfile by default so still you can generate docs by running following rake task
1
|
|
It has been removed and rails executable is moved to bin/ dir
This directory has been changed quite a bit.
Now we have controllers and models in place of functionals and units
We also have helpers and mailers dir under test by default
Performance test has been extracted to a new Gem. So performance dir is not under test by default
Corresponding rake task for test has also changed –:
1 2 3 4 |
|
Rails plugins are already gone away so this dir is no more needed.
Our favorite rails command ‘scaffold’ gives us few new files. Lets create new scaffold
1
|
|
You will see there are two new files
These files can be used for responding data in JSON format. These are generated by jbuilder Gem. It is included in Gemfile by default.
I hope this post will be useful for you. If there is any mistake in this post just let me know.
There is lot to learn about rails 4. If you want here are some links
]]>You can find blog on RubySource
]]>
In Rails we have Ploymorphic Association whenever we need to connect one model to more than one model.
I had a situation where i need polymorphic association with has_many :through
Here I am showing an simple example of polymorphic association with has_many :through
We have Contact
, Plan
and Template
as a ActiveRecord
Classes.
We have following scenarios.
Plan has_many Contacts
Contact has_many Plans
Template has_many Contacts
Contact has_many Templates
which is vice versa of 3.So here is the main problem. Here to solve this we need two more tables other then Plans
, Contants
and Templates
.
My Plan
Model looks like:
1 2 3 4 |
|
My Template
Model looks like:
1 2 3 4 |
|
My Contact
Model looks like:
1 2 3 4 5 6 7 8 |
|
And here are two different tables for handling many_to_many
Handling Plan
and Contact
here.
1 2 3 4 |
|
Handling Template
and Contact
here.
1 2 3 4 |
|
This problem can be solved using only one table. Just we need to mark that table as a polymorphic.
We are calling that tables as contact_details
. Here is class looks like.
1 2 3 4 |
|
Migration should look like:
1 2 3 4 5 6 7 8 9 10 |
|
Now change your Contact
model like:
1 2 3 4 5 6 |
|
Now change your Plan
model like:
1 2 3 4 |
|
Same way Template
model like:
1 2 3 4 |
|
So you can see we can use one table(contact_details) for both plan and template
1 2 3 4 5 6 7 8 9 10 11 |
|
so if you have accepts_nested_attributes_for :template then you can create template for contact in a form
1
|
|
it will create an entry in templates table and and entry in contact_details
So in this way we dont need to write much code.we can reduce tables number
I hope it will be helpful for you
Reference links :
]]>
1. Follow law of Demeter(In rails it means use only one dot)
1
2
3
4
5
6
7
8
9
10
11
12
class Author < ActiveRecord::Base
has_many :books
has_one :address
end
class Book < ActiveRecord::Base
belongs_to :author
end
class Address < ActiveRecord::Base
belongs_to :author
end
So if in a view we have something like
1 2 3 4 5 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
So if in a view we have something like
1 2 3 4 |
|
Now we have just only dot.Here :allow_nil option prevents the error call method on nil object
2. Use callback and validation.instead of writing large code in your method
1
2
3
4
5
6
7
8
9
10
class User < ActiveRecord::Base
email_confirmation
attr_accessor :email_confirmation
def user_save
if email && email_confirmation && save
#send_email
end
end
end
1
2
3
4
5
6
7
8
9
10
11
12
class User < ActiveRecord::Base
validates :email, :confirmation => true
validates :email_confirmation, :presence => true
after_create :send_email
private
def send_email
#send_email
end
end
3. Include Modules
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Order < ActiveRecord::Base
def self.find_purchased
# ...
end
def self.find_waiting_for_review
# ...
end
def self.find_waiting_for_sign_off
#.....
end
def self.find_waiting_for_sign_off
#...
end
def self.advanced_search(fields, options = {})
#...
end
def self.simple_search(terms)
#...
end
def to_xml
#...
end
def to_json
#...
end
def to_csv
#...
end
def to_pdf
#...
end
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Order < ActiveRecord::Base
extend OrderStateFinders
extend OrderSearchers
include OrderExporters
end
# lib/order_state_finders.rb
module OrderStateFinders
def find_purchased
#...
end
def find_waiting_for_review
#...
end
def find_waiting_for_sign_off
#...
end
end
# lib/order_searchers.rb
module OrderSearchers
def advanced_search(fields, options = {})
# ...
end
def simple_search(terms)
# ...
end
end
# lib/order_exporters.rb
module OrderExporters
def to_xml
# ...
end
def to_json
# ...
end
def to_csv
# ...
end
def to_pdf
# ...
end
end
4.Use active record association
Rails provides us association very nicely.
1
2
3
4
5
6
7
8
9
10
11
class User < ActiveRecord::Base
has_many :blogs
end
class blog < ActiveRecord::Base
belongs_to :user
end
@user = User.find(params[:id])
@blogs = Blog.where(:user_id => params[:user_id])
Instead of doing this.do
1 2 |
|
5. Use Scope rather than writing complex finders
1
2
3
4
5
class Book < ActiveRecord::Base
def search_books(params={})
where('name like ? and price > ? and published_date > =?', "%#{params[:name]}%", 100,Date.today)
end
end
1
2
3
4
5
6
7
8
9
class Book < ActiveRecord::Base
def search_books(params={})
where('name like ? and price > ? and published_date > =?', "%#{params[:name]}%", 100,Date.today)
end
def search_by_published_date(date)
where('published_date > =?',date)
end
end
1
2
3
4
5
class Book < ActiveRecord::Base
scope :by_published_date,lambda{|d|{:where => ['published_date >= ?',d]}}
scope :by_name,lambda{|n|{:where => ['name like ?',"%#{n}%"]}}
scope :by_price,lambda{|p|{:where => ['price =?',p}}
end
1
Book.by_published_date(Date.today).by_name('rails').by_price(100)
6. Do Metaprogramming
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Plan < ActiveRecord::Base
ACTIVE='active'
INACTIVE = 'inactive'
IN_PROGRESS = 'in progress'
def active?
status == ACTIVE
end
def inactive?
status == INACTIVE
end
def in_progress?
status == IN_PROGRESS
end
end
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Plan < ActiveRecord::Base
ACTIVE='active'
INACTIVE = 'inactive'
IN_PROGRESS = 'in progress'
[ACTIVE, INACTIVE,IN_PROGRESS].each do |s|
plan_status = <<-EOF
def is_#{s}?
self.status == '#{s}'
end
EOF
class_eval plan_status, __FILE__, __LINE__
end
end
7. Use full text search engine
if you app require search based on all the attribute on model or something like that then writing messy code is not an good idea. Better way is to use any search engine like Solr, Sphinx
Search engine indexed the data.so it gives you results based on search query against any full words in the indexed data
I have covered most of the steps here to enhance your Rails Models and keep your Rails Models clean, Here are some links to read more about these things. Reference links :
Thanks for reading this post :–)
]]>rails runner
command simply loads the default Rails environment and then executes some specified Ruby code.
Some of use cases :
Showing here some code example for
Let’s say you want to generate a nightly report and send it out to multiple users
1
|
|
This will execute send_me!
method for DailyReport
class.
rails runner
will give us access to all rails environment so we can even use the Active Record finder methods to extract data from our application.
1
|
|
Here we are just listing out emails of all users in our system.
1
|
|
Output will be
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
A sample crontab to run that script might look like
1
|
|
This script will run daily to send out daily report.
The Rails Runner is useful for short tasks that need to run infrequently.
But jobs that require more heavy work are best handled by other libraries.
I use rails runner
whenever I need to run a small task.
Reference links :
There are other better library available for handling background process. But here I wanted to talk about rails runner
You might need to respond both in JSON and XML or might be only JSON in your controller.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
You can see here that in both the action we are responding with HTML and XML.
Rails 3 introduced a new set of methods called responders
that abstract the code so that the controller becomes much simpler.
Here is our example written using responders
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
This looks more cleaner No ?
The entire respond_to
block is gone now.
I know this feature is very old. But it’s very important to use this feature for more cleaner code.
Reference links :
]]>Github uses the OAuth2 flow. First of all you have to register your app with Github GitHub Applications Page. Create a new application here and get Client ID and Secret. Here is how can you obtain Client ID and Secret from Github.
Steps to use these in your app.
1
rails new GithubAuthApp
omniauth-github
1
gem "omniauth-github"
1
2
3
4
use OmniAuth::Builder do
provider :github, XXXX, YYYY
end
All done start you server
1
|
|
Just open your app in browser with URL
1
|
|
You will be redirecting to Github for authentication.
After success your app will redirect to your given callback URL with information and token!
At OmniAuth.org you can try out different -2 Strategies.
Useful links :
1 2 3 4 |
|
lambda
1 2 3 4 |
|
Difference between both of themin Ruby-1.9.3
1 2 3 4 5 |
|
1 2 3 4 5 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 |
|
so difference is lambda return within it but the proc return from where it is called if we modified test_proc method like
1 2 3 4 |
|
now the output will be –:
1 2 |
|
1 2 3 |
|
READMORE You can call this proc by 4 ways
1 2 3 4 |
|
Asset Pipeline
Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets. Rails 3.1 is integrated with Sprockets through Action Pack which depends on the sprockets gem, by default.
Asset Organization
In Rails 3.1-:
There are three directories
so if you want to access application.css in app/assets/stylesheets.you can just access the url localhost:3000/assets/application.css
you can add additional path to the pipeline in config/application.rb. For example:
1
config.assets.paths << Rails.root.join("app", "assets", "flash")
Manifest files and Directives
Assets In Development
In Development environment all assets are served as individual files For Example in app/assets/javascripts/application.js
1
2
//= require core
//= require blogs</blockquote>
after converting in HTML it will look like
1
2
<script src="/assets/core.js?body=1" type="text/javascript"></script>
<script src="/assets/blogs.js?body=1" type="text/javascript"></script>
If turn off debugging by setting config.assets.debug = false in config/environments/development.rb above file will generate
1
2
<script src="/assets/application.js?body=1" type="text/javascript"></script>
In Production
Rails server complied assets using Fingerprinting Scheme
In Fingerprinting scheme a hash of content is attached to the end of file to uniquely identified the file blogs-908e25f4bf641868d8683022a5b62f54.css
Prior rails 3.1 a time stamp query string is attached to file name stylesheets/blogs.css?1409495796
For example –:
1
2
3
<%= javascript_include_tag :application%>
<%= stylesheet_link_tag "application" %>
It will compile in to
1
2
3
<script src="/assets/application-908e25f4bf641868d8683022a5b62f54.js" type ="text/javascript"></script>
<link href="/assets/application–4dd5b109ee3439da54f5bdfd78a80473.css" media="screen" rel="stylesheet" type="text/css">
The fingerprinting behavior is controlled by the setting of config.assets.digest setting in Rails (which is true for production, false for everything else)
Useful Links –: ]]>you need to inlcude javascript files
1 2 3 |
|
Inclue CSS files
1
|
|
1 2 3 4 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Here my_class_method is Class Method.we can define more class methods in module ClassMethods
Validations and call backs are called without prefix ‘self’. so for validations and call backs we have to explicitly set the class
1 2 3 4 5 6 |
|
Routes for CRUD actions
1
|
|
Also define for multiple resources
1
|
|
Nested Routes
1 2 3 |
|
Member and collection
1 2 3 4 |
|
if we have more than one collection or member functions
1 2 3 4 5 6 7 8 9 10 |
|
Named Routes
1
|
|
Adding :as makes it a named route so that we can use history_path or history_url in our application.
Route for Root
1
|
|
Constraints and Parameters in routes
1
|
|
Here email is mandatory parameter and first_name and last is optional parameter and in constraints email format is defined
]]>