×

Get the Blog Updates

Your information will not be shared with any 3rd parties under any circumstances.
Cancel
Image Image Image Image Image
Scroll to Top

To Top

Scroll to Top

To Top

Search Results for: label/Ruby developer

10

Jul
2013

No Comments

In Ruby on rail

By Srikant M.

Why Rails framework popular among Ruby developers

On 10, Jul 2013 | No Comments | In Ruby on rail | By Srikant M.

Introduction:

Most companies whether it’s a start-up or an established enterprise have evidently landed to the conclusion that, Ruby on Rails is the most viable option for rapid and cost efficient web app development.

Ruby on Rails or simply called ‘Rails’ is an open-source, full-scale multilevel web app framework that implements MVC development architecture, for the Ruby programming language and is supported by a strong community around it.

Let’s take a quick look on the features of ROR:

Mature Framework

Ruby on Rails was first released in 2003, which possessed several large and actively maintained APIs those make application development faster, easier and more manageable. One of the best examples is CSRF (Cross Site Request Forgery) protection; using which, you don’t have to do anything to add CSRF. Active Record is an extremely powerful feature in terms of building the usable data models.

Speed and Development

Generators/Scaffolding:

It’s a rapid prototyping tool; Rails’ scaffold will generate a starting point that allows us to list, add, remove, edit, and view things. It will explain the command, the model name and related database table, naming conventions, attributes and types.

The generated script will produce files of Ruby code that the application can use to interact with the database. It is somewhat less convenient than dynamic scaffolding, but gives the programmer the flexibility of modifying and customizing the generated APIs.

Gems/Plugin:

Ruby gems are highly portable chunks of Ruby code that can be used inside any Ruby script or application.

Rails plugins have the flexibility to hook into every part of Rails, including generators, rake tasks and tests/specs. They are specific to Rails and could not be (directly) used with another Ruby framework like Merb, Sinatra, etc.

Active Record ORM:

Object-Relational Mapping (ORM) is a technique that connects the rich objects of an application to tables in a relational database management system.

Active record pattern is an architectural pattern found in Ruby on Rails that stores its data in relational databases. It relies heavily on the naming in that it uses class and association names to establish mappings between respective database tables and foreign key columns.

Integrated testing tools:

Rails features a convenient testing tool, for which, it automatically starts producing the skeleton test code in background whilst you are creating the application models and controllers.

Rails tests can also simulate browser requests and thus you can test your application’s response without having to test it over browser.

Some convenient tools for testing Rails application:

  • Test Unit
  • RSpec
  • Cucumber
  • Mocha
  • Flexmock
  • Factory Girl

Version Control Systems:

There are numerous version control systems. CVS was the first system widely used in the open-source community. Several years ago, it was largely replaced by Subversion (SVN). And in early 2008, most of the Rails world moved to a newer version control system, called GIT.

GIT is the usual “best choice” if you are new to Ruby, because nearly all code you’ll have to fetch as examples/libraries will be available via hosted GIT repositories.

Conclusion

With Ruby on Railsproviding a programming framework that includes reusable, easily configurable components commonly used for creating web-based applications, it is gaining traction with developers.

From the recent studies on the job growth trends, it is seen that Ruby on Rails developers are a very hot commodity. Ruby as the language of the cloud, the job market will continue to show high demand for Rails developers. It’s nearly impossible to be an unemployed Ruby on Rails developer.

RoR_graph_new1-1024x532 (1)

 

Tags | ,

05

Apr
2013

No Comments

In Ruby on rail

By Jay Dee

Ruby on Rails releases fixes for DoS, XSS Vulnerabilities

On 05, Apr 2013 | No Comments | In Ruby on rail | By Jay Dee

ror_development_123

In 18th March, Ruby on Rails released four new versions along with fixes for a number of vulnerabilities, which could have lead to denial of service attacks and XSS injections. According to a post in company’s blog a total of 4 vulnerabilities were addressed in version 3.2.13, 3.1.12 and 2.3.18 of Rails. The company wrote “All versions are impacted by one or more of these security issues,”

The patches were released for symbol denial service (DoS) vulnerability (CVE-2013-1854) in ActiveRecord function and for two cross-sites scripting vulnerabilities i.e. sanitize helper (CVE-2013-1857) and sanitize_css method in Action Pack (CVE-2013-1855).

According to one of the warnings, an additional XML parsing vulnerability in JDOM backend of ActiveSupport could have also allowed attackers to perform denial of service attack when using JRuby (CVE-2013-1856) or could have enabled to gain access to files stored in the app server.

The XSS vulnerability could have allowed attackers to embed tag URL, which executes arbitrary JavaScript code.

The XSS vulnerabilities in particular could have allowed an attacker to embed a tag containing a URL that executes arbitrary JavaScript code.

Ruby on rails developer have fixed a number of similar issues in Ruby on Rails last month, which also included a YAML issue in ActiveRecord that lead to remote code execution

Tags | , ,

25

Apr
2014

No Comments

In Ruby on rail

By Srikant M.

Top 5 reasons why web development is faster with “Ruby on Rails”?

On 25, Apr 2014 | No Comments | In Ruby on rail | By Srikant M.

Ruby-on-Rails-150x150Ruby on Rails aka “RoR” is an open-source MVC framework built using the Ruby programming language.

It is considered as the epitome of the latest generation of high-productivity, open source web development tool. The growing demand for Ruby on Rails has been driven by successful RoR development companies like Andolasoft, who benefit from the speed and agility of building applications in Rails, which results in increased productivity and company growth.

1. Framework built on Agile methodology

RoR is faster because the framework was built based on Agile development methodology, best practices are emulated so web development is done with high quality and speed.

RoR framework includes support programs, compilers, code libraries, tool sets, and application programming interfaces (APIs) that bring together the different components to enable development of a project or solution.

Sites that would traditionally take 12 weeks to build can commonly be launched inside of 6 weeks with Ruby on Rails, saving you cost close to 50%.

2. Less code writing

It has all the code libraries pre-loaded while creating a rails structure. So you need to write some command, which would execute and generate a skeleton of the application and modules. This is what makes the process of web development faster.

Rails is easier because it allows migrations which makes deployment of database changes easier than any open or commercial solution available.

  • Adopting principle of DRY
    It also adopts the principle of “Don’t Repeat Yourself” so all information can be retrieved from a single unambiguous database which tends to easier development.
  • Easy configuration
    A key principle of Ruby on Rails development is convention over configuration. This means that the programmer does not have to spend a lot of time configuring files in order to get setup, Rails comes with a set of conventions which help speeding up development.
  • Modular design
    Ruby code is very readable and mostly self-documenting. This increases productivity, as there is little need to write out separate documentation, making it easier for other developers to pick up existing projects.
  • Designer Friendly Templates
    HTML templates is a core feature of Rails. It allow templates to be composed of a base template that defines the overall layout of the page,the base template is called a “layout” while the individual page templates are “views”. The Rails application retrieves the list of tags from the database and makes it available to the view.The section of the view that renders these category is:
    <%= render :partial => 'category' %>

    This refers to a Ruby partial, a fragment of a page, which is contained in _category.html.erb. That file’s content is:

<h3>categories</h3>
<p class="categorylist">
<%= render :partial => 'categorylist', :collection => @category %>
</p>
  • This generates the heading then refers to another partial, which will be used once for each object in the collection named “categorylist”.

3. Third Party Plugin/Gem Support

Mature plugin architecture, well used by the growing community. Rails plugins allows developer to extend or override nearly any part of the Rails framework, and share these modifications with others in an encapsulated and reusable manner.

Rails community provides a wealth of plugins as Ruby Gems that you simply add to your project Gem-file and install. This significantly accelerates development and maintenance time as you’re not trying to integrate disparate libraries, it’s already done for you.

 

4. Automated Testing

Rails has developed a strong focus on testing, and has good testing suit in-built within the frameworks.

Rails makes it super easy to write your tests. It starts by producing skeleton test code while you are creating your models and controllers.

Rails ships with a built-in test suite. There are many tools available in the market for testing Rails application as mentioned below with other web apps from many different aspects.

  • Rspec
  • Cucumber
  • Test Unit
  • Shoulda
  • Selenium (not really a ruby thing but more of a web thing)

But if you are new to testing we highly recommend you start with learning Rails own testing suite before start using other tools

5. Easier Maintenance

Once site launches, future modifications to your site (e.g., adding new features, making changes to the data model) can be made more quickly, for the same reasons noted above.
New features can be added quickly and maintaining applications over time can also be more cost-effective.

If you like this one, you might also like Why Rails framework popular among Ruby developers and The Best practices for Rails App Development .

Like this blog? I’d love to hear about your thoughts on this. Thanks for sharing your comments.

 

 

Tags | , , , ,

22

Sep
2010

No Comments

In Ruby on rail

By Jay Dee

The Era of Ruby on Rails Development

On 22, Sep 2010 | No Comments | In Ruby on rail | By Jay Dee

rails_image1With the advent of Ruby on Rails around 2006, it has revolutionized the sphere of web development. Built on MVC (Model-View-Controller) architecture, this relatively new technology in the field of web development, has appealed to numerous developers. Programmers, who were accustomed to writing thousands of lines codes in technologies like PHP and JAVA, were spellbound by this frameworks agility and features to create a full-fledged database backed application within a few hundred lines of code.
Application which normally would have taken months or even years to complete, can now not only be wrapped up within days and months but also with considerably less number of developers.Rails is backed up by the powerful object oriented language Ruby, on which it is based. It also leverages the extensive patronage of Ruby for meta programming. It makes optimum use of code generation features, which eases out to complete applications and promote agile programming techniques.

Rails development is also unique in the field of web application because it makes use of two key design features which are DRY or “Don’t Repeat Yourself” and CoC or “Convention over Configuration”. Agile Development Methodology, combined with DRY and CoC, not only helps ruby on rails engineer’s to develop dynamic web application economically, in less time & code but also facilitates code reusability in the development process.

Andolasoft Inc offers fast and high class Ruby on Rails development to startup and established businesses, groups, etc.

Tags | , ,

09

Mar
2011

No Comments

In Ruby on rail

By Jay Dee

Ruby Rails Development Sphere & Associated Myths

On 09, Mar 2011 | No Comments | In Ruby on rail | By Jay Dee

rorRuby on Rails development is fast changing the norms of web development across the globe. Companies around the world are fast catching up with this magical web development framework for exploring and executing its true potentials; thereby serving their clients with really cost-effective, quick and dynamic Ruby on Rails Applications. Ruby developers and Rails developers are becoming the most sought after skilled professionals, for Software companies to hunt for.

Ruby on Rails, being an Open Source tool, coupled with fast development life cycle, requires much less resources in terms of Programmers and man-hours; which results in the service provider and client being the ultimate beneficiaries. Silicon Valley based leading Software firm, Andolasoft Inc. is a formidable force to reckon with as far as Ruby on Rails development is concerned. With a vast pool of Programmers as well as Domain Leads, this fairly young Enterprise has carved out many Social Networking Sites, Social Media Marketing web apps. Andolasoft services include but not limited to RoR Development, RoR Application Migration, Social Media Integration, System Administration, Redesigning of Existing Apps, Performance Improvement Related Tasks and Rescue Support.

Irrespective of all its popularity, RoR also has few myths related to it.

Applications can be built hundreds of thousands times faster than other technologies: The fact is Rails doesn’t write the code automatically. It just lets the developers work easy by managing certain functionalities; thereby allowing them to focus on other crucial modules. It also manages the laborious part of lifting of user interactive modules. Having said that, such myths reflects a wrong opinion upon customers, whose expectations sometimes become too high for the service providers.

Even Non-programmers can build web applications: This is by far the silliest perception about Rails development. Although the simplicity of this framework and clean syntax of ruby language assist in quick development, but still experience is required as far as writing code is concerned. Rails developers do need to write new and unique code, apart from using the Rails conventions on top a comprehensive web development framework.

Tags | , ,

11

Oct
2012

No Comments

In Ruby on rail

By Jay Dee

Usage of PDFKit with Rails 3.2.8 and Ruby 1.9.3

On 11, Oct 2012 | No Comments | In Ruby on rail | By Jay Dee

PDFkit is a powerful library which generates PDF from HTML + CSS. It uses “wkhtmltopdf” on the back-end which renders HTML using Webkit. Here is a simple example which describes the installation of “wkhtmltopdf” and usages of pdfkit. I have used rails 3.2.8 and ruby 1.9.3 as my environment.

Step-1:

Install the “wkhtmltopdf” library

Download the “wkhtmltopdf” library from the link
http://code.google.com/p/wkhtmltopdf/

Windows

  • Download the exe file and install it.
  • Remember the installation path

Linux

  • Download the binary for your architecture at the http://code.google.com/p/wkhtmltopdf/downloads/list
  • Extract the file to a directory that is in your PATH, such as /opt or /usr/local/bin and run from there.

For Debian/Ubuntu use the following command:

apt-get install wkhtmltopdf

Step-2: Installing PDFKit

In your bundle file write

gem 'pdfkit'

Then install

bundle install

Step-3: Configuration of PDFKit

Create a new file “pdfkit.rb” in “config/initializers/” path and write the following

If you are in windows then you need to give the path to the exe file generated after installation. If you are in linux and the path is set as the default path then you don’t need to give the path.

PDFKit.configure do |config|
config.wkhtmltopdf = 'C:\Program Files\wkhtmltopdf\wkhtmltopdf .exe'
config.default_options = {
:page_size => 'Legal',
:print_media_type => true
}
# config.root_url = "http://localhost" # Use only if your external hostname is unavailable on the server.
end

Step-4: Middleware Setup

Write the following in the “config/application.rb

require 'pdfkit'
 
config.middleware.use PDFKit::Middleware
config.threadsafe!

Step-5: Usages

Creating PDF in a file path

Now to generate the pdf file by writing down the following codes on one of your controller actions

kit = PDFKit.new"<h1>Hello</h1><p>This is PDF!!!</p>"
file_path = your_file_path
pdf = kit.to_file file_path

Now you can find the PDF file being generated on the file path.

Displaying PDF on browser

<p id="pdf_link"><%= link_to "Download Invoice (PDF)", order_path(@order, :format => "pdf") %></p>

Your PDF will be displayed on the browser.

You can also add “.pdf” to any of our application’s URLs to get a PDF version of that page.

Tags | , , ,

13

Jun
2012

No Comments

In Ruby on rail

By Jay Dee

Successful Mobile App and Ruby on Rails Projects

On 13, Jun 2012 | No Comments | In Ruby on rail | By Jay Dee

Rails3_logo

Andolasoft is remarkable and energetic to start the ball rolling in numerous products in mobile application development and Ruby on rails development arena.

Among them Christmas Tree Puzzle game app, job management app for IPhone. Also Social email reminder app, Social media Job portal app in RoR are getting used by lots of people everyday.

Some of our new projects are product based and we are focusing on the advance technology of mobile and web application development like IPhone, Android, RoR, PHP/CakePHP. Very soon we are going to launch/release some new apps those are under development and will available in the market very shortly. Check out our recent portfolio and domains and technologies. We’re also growing by increasing our team size. We’ve a team of dedicated and skilled developers and designers who’re helping Andolasoft to do the job perfectly in right time. Quality assurance is one of our aim for all projects with a quick turnaround period. Continuously we keep hunting and hiring right folks with mobile as well as web technologies. Please check out current job openings.

Tags | , , ,

14

Mar
2011

No Comments

In Ruby on rail

By Jay Dee

Security Issues Related to Ruby on Rails Applications

On 14, Mar 2011 | No Comments | In Ruby on rail | By Jay Dee

Rails3-123Security of any software product or application is something which every software solution provider is wary of. It is no different in the case of a Ruby on Rails application. Even after an application is successfully developed and deployed, there can be possibilities for many unseemly activities. US based high end software solution provider Andolasoft.Inc sheds some light on some of the basic precautions that are worked upon before deploying an application. The Company’s Rails developers pay special attention to security issues in every undertaken venture.
Authentication and authorization of User model are two different things. Actions like create/update/delete always need to be protected. Even popular plug-ins like Restful authentication and Clearance only authenticate whereas providing no helper methods for authorization.

Mass assignment of sensitive attributes from re-assignment should be protected. This can be taken care of by disabling mass assignment with the help of attr_accessible or attr_protected in the respective models. Attributes like account_id’s and user_id’ should be protected. Also disabling updates on protected attributes can be by using attr_readonly, so that the Ids don’t get updated once set.

Content types of files being uploaded can be faked, so uploaded files should be placed in protected directories or servers. Also file extensions should be checked and the web server should be disabled so as not to execute such files in the uploaded directories.

Sessions are prone to vulnerabilities like hijacks, replaying cookies and session fixation. Extra caution must be taken regarding storing data in sessions. Active record Objects should never be stored in sessions which might change that Object’s behavior while migration and future code changes. Best practice is to only store the ids of the records. Also sensitive data like User access privileges and money based information should not be stored in sessions.

Tags | , ,

08

May
2010

No Comments

In Ruby on rail

By Jay Dee

Why choose Ruby on Rails for your web app

On 08, May 2010 | No Comments | In Ruby on rail | By Jay Dee

rails_image2

Ruby on Rails, popularly known as RoR, is developed using the Model-View-Controller (MVC) design pattern along with the agile development methodology. Ruby on Rails is intended to emphasize Convention over Configuration (CoC), and the rapid development principle of Don’t Repeat Yourself (DRY).


Benefits of Ruby on Rails

  • Development Speed

Ruby on Rails allows features to be developed quickly by using existing methods and components with the help of modular design. The factors behind its time saving results include- modular design, leaner code base and availability of existing gems/plug-ins. So the development cycles in Rails are shorter as compared to it’s counterparts.

  • Flexibility

In Rails, there are lots of in-built components of specific functionalities already available. These modules can be reused in development rather than building everything from scratch. Ruby on Rails offers the ability to easily modify a web application in response to customers needs.

  • Cost-effectiveness

In addition to the flexibility and development speed, Ruby on Rails is an open source web application framework which helps in developing cost-effective web applications without sacrificing performance, speed and quality.

  • High code quality

The Ruby development community is very active and responsive. There are a lot of resources available over the Internet and any problem encountered during ROR development can be easily solved by communicating to the community. Also security updates and bug fixes are released regularly which helps in maintaining top notch code quality for application development.

  • Industry support

There are many Ruby on Rails web hosting/consulting companies such as AWS (amazon EC2), Heroku & EngineYard offering cloud based services. They offer scalable hosting environment and provide support for development and deployment of RoR applications.

Andolasoft offers quality rails development service. We specialize developing database driven web application in a efficient and hassle-free way. Visit our portfolio and Contact us for further details.

SEE ALSO: Why Rails framework popular among Ruby developers

Tags | , ,

29

Jun
2013

No Comments

In Ruby on rail

By Srikant M.

What new features you will get in the latest release of Rails4

On 29, Jun 2013 | No Comments | In Ruby on rail | By Srikant M.

Rails_4-300x137

Introduction:

Finally, the most awaited Rails 4.0 version has been released by the Rails team on 25th of June. Rails 4 has got huge changes. There are tons of new features available, which can make your life as a Rails developer a lot easier. We will talk about the most exciting features in Rails 4 and why you should upgrade from Rails 3 version as soon as possible.

New features of Rails4

1. Ruby Versions

It is essential to note that Rails 4 would require Ruby 1.9.3 or higher, in fact Ruby 2.0.0 is recommended for your Rails 4 apps.

2. ‘Gemfile’

Rails now uses a ‘Gemfile’ in the application root to determine the gems you need for your app to start. This ‘Gemfile’ is processed by the Bundler gem, which then installs all the dependencies. It can also install all the dependencies locally to your app so that it doesn’t depend on the system gems.

Read Also: How to do tagging in Rails with gem ‘Acts_as_taggable_on’?

3. ‘Threadsafe’ by Default

Rails 4 will be thread-safe by default i.e. removing overhead and improving the performance on threaded servers, like thin and puma. You will have to ensure that your application and its dependencies are thread-safe, in other words, avoiding global state e.g. class or global variables.

4. No More vendor/plugins

Rails 4.0 will no longer support loading of plugins from vendor. You must replace any plugins by extracting them to gems and adding them to your ‘Gemfile’. If you choose not to make them gems, you can also move them into a different directory such as lib/my_plugin/* and add an appropriate initializer in config/initializers/my_plugin.rb.

5. New Testing Directories

The biggest change made to the testing of Rails 4 app is not the swapping of the testing framework, rather the testing folder structure. The test folder will now have a structure very similar to RSpec:

  • controllers:
  • fixtures
  • helpers
  • integration
  • mailers
  • models

Developers will no longer have to worry if the test is “functional” or a “unit”. The structure provides a clear separation of where the tests in your application should go.

6. Strong Parameters

In Rails 4, a new pattern has been introduced to secure your models from mass assignment. You can filter the parameters passed to your model in the controller instead of ‘whitelisting’ the attributes in your model using “attr_accessible”.

class PostController < ApplicationController
 def create
 @post = Post.create(params[:user])
 end
end

You can protect against unexpected input with declarations in the model using “attr_accessible”.

attr_accessible :title, :description

In Rails 4, you don’t need to worry about unexpected input attributes in your model anymore.
Strong Parameters gem moves user input into the controller.

class PostController < ApplicationController
 def create
 @post = Post.create(post_params)
 end

 private
 def post_params
 params.require(:post).permit(:title, :description)
 end
end

The “params hash” in your controller is not a normal hash. It’s actually an instance of ActionController::Parameters, which exposes the “require” and “permit” methods.

The “require” method ensures that the specified key is available in the “params” hash, and raises an ActionController::ParameterMissing exception if the key doesn’t exist.

The “permit” method protects you from unexpected mass assignment.

7. Renamed Callbacks

Action callbacks in controllers are now renamed from *_filter to *_action

Example:

before_filter :before_action
arround_filter :arround_action
after_filter :after_action

All existing *_filter methods will still work with no deprecation warnings. However, It would recommend to replace of *_filter calls to *_action

8. Rails 2 Model.find(:[all|:first:last]) syntax is now deprecated.

9. Deprecated dynamic finders

Rails 4 deprecates all dynamic finder methods (with the exception of find_by and find_by_…). Instead, you’ll use where

find_all_by_... => where(...)
scoped_by_... => where(...)
find_last_by_... => where(...).last
find_or_initialize_by... => where(...).first_or_initialize
find_or_create_by... => where(...).first_or_create
find_or_create_by_...! => where(...).first_or_create!

The deprecated finders gem will be included as a dependency in 4.0 and removed in 4.1. The gem, however, will be around and maintained until 5.0.

10. Queuing system

Rails4 added the support for a queue to run background jobs. The queuing API is very simple. The ActiveSupport::Queue class comes with a push method that accepts any object, as long as that object defines a run method.

Example
Let’s say that you have a job class TestJob that prints the name of an author

class TestJob
 def run
 puts "I am running!"
 end
end

You can queue a job to print “I am running!” in the background by pushing an instance of that class to Rails.queue:

Rails.queue.push(TestJob.new)
"I am running!"

The job will run in a background thread and it will not block any of your operations.

11. Live Streaming

Live Streaming is a major new feature in Rails 4. It facilitates you to stream data to the browser. Enabling live streaming requires you to mix in the ActionController::Live class in your controller.

class MyController < ActionController::Base
 include ActionController::Live
 def stream
 response.headers['Content-Type'] = 'text/event-stream'
 100.times {
 response.stream.write "hello world\n"
 sleep 1
 }
 response.stream.close
 end
end

It will stream the string “hello world” to your client 100 times.

You should take notice of following things

  • Manually close the stream after you are done streaming in the browser.
  • Headers must be written first before writing anything to the client.
  • You will need a concurrent Ruby web server, such as puma.io, Rainbow or Thin. Using the default ‘WEBrick’ server won’t work, since it buffers all the output. Also note that Unicorn won’t work either, since it kills the connection after 30 seconds.
  • All controllers that include ActionController::Live would be executed in another thread, so make sure your code is thread-safe.

12. Rails 4 and Hstore from Postgres 9.2

ActiveRecord in Rails 4 will now support the PostgreSQL hstore extension. This database extension allows a new data type for a column in PostgreSQL called ‘hstore’ which effectively represents a string-only hash. For most purposes this would be similar to serializing data in a text column, but the fact that this is now a native datatype, it would grant a huge performance boost and the capability to query against it directly. You can now have a hint of a schema-less database available to your application without needing to perform a full upgrade to MongoDB, CouchDB, Riak or other similar schema-less data store.

13. Cache Digests (Russian Doll Caching)

Make it super easy to do Russian Doll-caching through key-based expiration with automatic dependency management of nested templates

14. Turbolinks

Now you can speed-up the client-side with ‘Turbolinks’. It essentially turns your app into a single-page ‘JavaScript’ application in terms of speed, but with none of the developmental drawbacks (except, maybe, compatibility issues with some existing JavaScript packages).

15. Routing Concerns

In Rails 4, routing concerns has been added to the router. The basic idea is to define common sub-resources (like comments) as concerns and include them in other resources/routes.

16. Rails3 code

resources :posts do
 resources :comments
end
resources :articles do
 resources :comments
 resources :remarks
end

In rails4 the concern routes will only be included within a resource by passing it to the routing option :concerns. The :concerns option can accept one or more concerns.

concern :commentable do
 resources :comments
end
concern :remarkable do
 resources :remarks
end
resources :posts, :concerns, :commentable
resources :articles, :concerns =>[:commentable, :remarkable]

Why we should upgrade to rails4?

Rails4 is recommended to be used with Ruby 2.0.0. It stopped supporting Ruby 1.8.x after Rails 3.2. Ruby 1.9.2+ will be supported until Rails 5 is released!

Aware of any other not-so-obvious features? Please post it in the comments below.

Tags | ,

09

May
2013

No Comments

In Ruby on rail

By Srikant M.

Steps to execute pagination using “Kaminari” gem in Rails3

On 09, May 2013 | No Comments | In Ruby on rail | By Srikant M.

Rails3-123

Kaminari” is a clean, powerful, customizable and sophisticated pagination for the modern web applications. Here we have to bundle the gem and the models that are ready to be paginated and no extra configuration is required for the process.

Key Features:

  • Easy to use.
  • Customizable engine-based I18n-aware helper.
  • The pagination helper outputs the HTML5 <nav> tag by default and the helper supports Rails 3 unobtrusive Ajax.

Recommended Reading: AJAX Pagination using jQuery in Rails3

Here are the steps to implement “kaminari gem” in a Rails app.

Step#1

  • Put this code in your Gemfile:
gem 'kaminari'
  • Run “bundle install”

Step#2

  • Modify the controller as mentioned below
@blogs = Blog.order("name").page(params[:page])

Step#3

  • Now, add the paginate helper method in your listing page which is provided by Kaminari, by passing in the list we’re paginating.
<%= paginate @blogs%>

Step#4

  • When the page reloads, the pagination links will be visible. Kaminari will show 25 items per page by default, but we can easily change that by calling another scope called “per” as mentioned below.
@blogs = Blog.order("name").page(params[:page]).per(10)
  • Now it should display 10 items per page.

Step#5

  • You can configure the below mentioned default values of kaminari by running the command
rails g kaminari:config

It’ll generate a file “kaminari_config.rb” in your config/initializers folder with the following code snippet as commented.

default_per_page   # 25 by default
max_per_page       # nil by default
window             # 4 by default
outer_window       # 0 by default
left               # 0 by default
right              # 0 by default
page_method_name   # :page by default
param_name         # :page by default
  • Next, you can change the values according to your requirement.
  • If you change your view page like:
<%= paginate @blogs, :window => 2 %> 
  • The output will be:
« First ‹ Prev 1 2 3 4 5 … Next › Last »
  • There are some other custom attributes you can use in view page like:
<%= paginate @users, :outer_window => 3 %>
<%= paginate @users, :left => 1, :right => 3 %>
<%= paginate @users, :params => {:controller => 'foo', :action => 'bar'} %>
<%= paginate @users, :remote => true %> 

Kaminari also includes a handy template generator. You can override them by running following command.

rails g kaminari:views default

It’ll generate a “Kaminari” folder in app/views with dependent files inside it.

I hope you liked it. If you want you can contact our experienced ruby on rails developer for your webs and mobile application.
Please leave your comment about this post on the comment section below.

Tags | ,

25

Jun
2013

No Comments

In Ruby on rail

By Srikant M.

How to configure Rails application with Puma and Ngnix on CentOS

On 25, Jun 2013 | No Comments | In Ruby on rail | By Srikant M.

Rails__new_0912

Puma is a multi-threaded high performance web server written in Ruby. Currently it is very popular in market as a ruby application server. We can use it for any kind of ruby web application that supports rack. Here, I have mentioned detailed steps to help you configure Rails application with Puma and Nginx on CentOS.

Steps to install Puma:

We can install puma via RubyGems.

1. Append the below line to your Gemfile, if you have Rails 3.0 or above:

gem 'puma', '~> 2.0'

2. Then we have to issue the below command to install puma

# bundle install

3. Now you can run your application with puma using the below command

# RAILS_ENV=production bundle exec puma -e production –b unix:///var/run/my_app.sock

You should see the following outcomes:

Puma 2.0.1 starting...
* Min threads: 0, max threads: 16
* Environment: production
* Listening on unix:///var/run/my_app.sock
Use Ctrl-C to stop

4. Press Ctrl-C and stop the process for now. We will start the server again after installation and configuration of ‘Ngnix’.

Steps to Install Ngnix:

1. To install Nginx on CentOS type below commands

# wget http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm
# rpm -ivh nginx-release-centos-6-0.el6.ngx.noarch.rpm
# yum install nginx

Configuring Ngnix:

1. First we have to create a virtual host file

#vi /etc/nginx/conf.d/my-NewProject.conf

2. Now add the below line to your config file (Change fields as your requirement)

upstream my_app
{
server unix:///var/run/my_app.sock;
}
server {
listen 80
server_name www.example.com; # change to match your URL
root /var/www/html/my_app/public; # I assume your app is located at this location
location / {
proxy_pass http://my_app; # match the name of upstream directive which is defined above
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

3.Then we have to restart the Ngnix

#service nginx restart

4.After restarting the Ngnix we need to again start puma

# cd /var/www/html/my_app/
# RAILS_ENV=production bundle exec puma -e production -b unix:///var/run/my_app.sock
Puma 2.0.1 starting...
* Min threads: 0, max threads 16
* Environment: production
* Listening on unix:///var/run/my_app.sock
Use Ctrl-C to stop</pre>
<pre>

Now you will be able to browse your application.

Type the Server Name you mentioned on your virtual host configuration.

For example: http://www.example.com

How to run Puma as a demon:

1. If you want to run puma as a foreground process (daemon) then start puma with –d option with the following command

# RAILS_ENV=production bundle exec puma -e production -d -b unix:///var/run/my_app.sock

2.To verify whether puma is running or not we have to issue the below command

# ps aux | grep puma
root  19119 13.1  1.3  43276 27792 ?   Sl   21:02   0:01 ruby /usr/local/rvm/gems/ruby-1.9.3-p0@tapas1/bin/puma -e production -d -b unix:///var/run/my_app.sock

Finally-steps to stop and restart our puma server

‘pumactl’ is a command line that helps to stop and restart the application server. It takes parameter from the file where we store the puma process state.

1.Currently we have to kill the running process of puma by issuing following command.

pkill –f puma

2. You can again verify the process is running or not by issuing the following command:

# ps aux | grep puma

3.Then start the puma with –S option

RAILS_ENV=production bundle exec puma -e production -d -b unix:///var/run/my_app.sock -S /var/run/my_app.state --control 'unix:///var/run/my_app_ctl.sock'

4.Now puma would generate the file /var/run/my_app.state like below content:

pid: 20937
config: !ruby/object:Puma::Configuration
options:
:min_threads: 0
:max_threads: 16
:quiet: true
:debug: false
:binds:- unix:///var/run/my_app.sock
:workers: 0
:daemon: true
:worker_directory: /var/www/html/my_app/
:environment: production
:state: /var/run/my_app.state
:control_url: unix:///var/run/my_app_ctl.sock
:control_auth_token: c0c3983017b972da3318a33349e8ee

5.Now, you can restart and stop your application with ‘pumactl’ using the file /var/run/my_app.state

a) To restart puma server issue the following command

bundle exec pumactl -S /var/run/my_app.state restart

b) To stop the puma server issue the following command

bundle exec pumactl -S /var/run/my_app.state stop

Following the above mentioned steps would result you with a clean configuration of Rails application with ‘Puma’ and ‘Nginx’.

Recommended Reading: New features of Rails4

Tags | ,

11

Jul
2013

No Comments

In Ruby on rail

By Jay Dee

The Best practices for Rails App Development

On 11, Jul 2013 | No Comments | In Ruby on rail | By Jay Dee

Rails_development_new_0912

Introduction:

“Rails” is an amazing framework to develop web applications quickly through its inbuilt helper libraries. However, there are certain best practices that you should follow to get your rails app perform better.

Conventional programming methods:

Most developers love to place the logic inside the controller and use the model for the “Active Record” operation only. This leads to a “Fat controller and skinny model” interface which eventually kills an app’s performance and looses the maintainability of the code. This way, application stops responding when the load is high.

What should be the best practices?

Below, I have mentioned some of the most essential and useful practices that should be followed by every Ruby on Rails developer.

Fat Model, Skinny Controller

Write all the non-response-related logics inside the model with nice and testable methods; and don’t forget to use comments. You should follow the Ruby on Rails motto i.e. “Fat Model, Skinny Controller”. Because the “skinny” controller offers a nice interface between the view and model.

By moving any logic that isn’t about the response (for example, setting a flash message, or choosing whether to redirect or render a view) to the model instead of the controller, not only you can reuse the codes where

possible but you’ve also made it possible to test your code.

Reusable Scopes

A scope is a set of constraints on database interactions (such as a condition, limit, or offset) that are chainable and reusable.

Let’s see a simple example:

def index
@paid_users= User.where(“is_active=? AND is_paid=?”,true, true).order(“name”)
@unpaid_users= User.where(“is_active=? AND is_paid=?”, true, false).order(“name”)

You can change it to this:

def index
@paid_users= User.paid.all
@unpaid_users= User.unpaid.all
end

Then, you can move the logic to your User model, where it might look like this:

scope :paid, lambda { where(“is_active=? AND is_paid=?”,true, true).order(“name”) }
scope :unpaid, lambda { where(“is_active=? AND is_paid=?”,true, false).order(“name”) }

Using the methods User.paid.all and User.unpaid.all, we’ve not only made it simpler to test our code, but also made it possible to reuse that same set of conditions in another location.

You should avoid the use of default_scope because:

  1. You can’t override default scope
  2. default_scope will affect your model initialization

Package Your Code into Gems and Plugins

Writing a particular set code more than once for different applications is exhausting as well as redundant, hence, it is advisable to create a plugin or gem to use it further. It will save your development time and effort.

Manage Your Attribute Access

While creating or updating an object, Rails usually assigns every attribute without checking the data. Validation only prevents the bad data but doesn’t exactly prevent it from overwriting an attribute that we don’t want to change.

To solve this issue, ActiveRecord is implemented which uses two methods: attr_protected and attr_accessibile.

Using attr_protected, you can declare a blacklist of variables you don’t want to be assigned and using attr_accessible, you can declare a list of variables that can be assigned.

By implementing above steps, you could prevent any mass assignment that could occur via your application’s forms; because if the form does not have the field for a given attribute, doesn’t mean a hacker can’t add it to the request.

From a security perspective, using attr_accessible and attr_protected forces you to think about what should be editable and how to protect the ways in which your class’s attributes are set.

Use Non-database-backed Models

In Rails, Model is not restricted to associate with table. To organize application logic, write it down by creating a new model.

Virtual Attributes

If you are manipulating data before passing it to a model, use virtual attributes instead.

Virtual attributes are a simple own getter and setter methods.

For example
To set a user’s name:

@user = User.new(params[:user])
@user.first_name, @user.last_name = params[:user][:name].split(" ", 2)

By using virtual method inside the model

def name=(value)
self.first_name, self.last_name = value.to_s.split(“ ”, 2)
end

Whenever you set the name attribute, your model will automatically set the first_name and last_name attributes for you, even though name doesn’t exist in the database.

Use Translations

Rails i18n framework makes it easy to declare the map of an abstract context to a string. All you need to do is maintain a YAML file of translations, and use I18n.t / t in your code where there is data shown to the use.

I18n is useful to avail your app to more locales.

Using of after_commit callback

Use “after_commit” instead of using after_create/after_update/after_destroy callbacks to start background processes. Because, in relational database, several operations are wrapped in one unit and pass or fail of transaction depends upon all the operations.

If you use after_create/after_update/after_destroy in first model and if any error occurs in the second model then the background process will raise NotFoundError.

Use select in ActiveRecord association

Use select with has_many and belongs_to on Active Record Associations to speed up the query.

For example:

class Patient < ActiveRecord::Base
belongs_to :physician, :select => 'id,name, surname'
end

class Physician < ActiveRecord::Base
has_many :patients, :select => 'id,name, physician_id'
end

Fix N+1 Queries

N+1 Queries is a serious database performance problem. Use “Bullet” gem to avoid N+1 query problem

Conclusion:

Employing the above mentioned Rails best practices would keep the code cleaner and reusable. The application performance would increases tremendously and the maintenance of the code will be easier.

Tags | ,

27

Jun
2014

No Comments

In Ruby on rail

By Srikant M.

Rails: Things you must know about TDD and BDD

On 27, Jun 2014 | No Comments | In Ruby on rail | By Srikant M.

What does “Testing” means ?

Testing of a product of services is an investigation to find out how well it is working against the expectation. Thus the quality of product can be assessed. Whether computer hardware or software development, testing is done at key checkpoints in the overall process to determine whether objectives are being met.

TDD-vs-BDD

What is TDD (Test-Driven Development) ?

TDD is a way of designing the code by writing a test which expresses what you intend the code to do. It defines a set of rules for developing software in which test cases are written before any code and the only code written will be enough to make the tests pass.

TDD is basically a software development technique that relies on the repetition of a very short development cycle. In this technique, first the developer starts by writing a failing automated test case (Red), implement the simplest solution that will pass the test cases (Green) and then finally improves or refactor the code (Refactor).”RED-GREEN-REFACTOR” is the main agenda for TDD.

Tools to use:
There are some popular gems available to implement TDD in Ruby on Rails like rspec-rails, capybara, factory_girl_rails, spork, launchy etc…

Example:
Below is the code snippet for writing controller tests, like this:

describe ArticlesController do
it "renders the index template" do
get :index
response.should render_template("index")
end
end

What is BDD (Behavior-Driven Development)?

BDD extends Test driven development by writing test cases in a way anyone can understand.With the help of BDD, software development is managed by both business interests and technical insight. It focuses and associates behavioral specifications with each unit of software under development.

Basically BDD is an Agile software development technique that encourages collaboration between developers, QA and non-technical or business participants in a software project. It extends TDD by writing test cases in a natural language that non-programmers can read. In other way it is like story writing.

The main thing to know is that BDD is meant to eliminate issues that TDD might cause.

Tools to use:
Some popular gems are available to implement BDD in Rails are rpsec-rails, factory_girl_rails, cucumber-rails, guard-cucumber, mocha etc…

Example:
Below is the code snippet for writing the BDD:

#articles.feature
Given an article exists called "Testing Demonstration"
When I visit the list of articles
Then I should see an article called "Testing Demonstration"

#article_steps.rb
Given /^an article exists called "(.+)"$/ do |title|
FactoryGirl.create(:article, title: title)
end
When /^I visit the list of articles$/ do
visit articles_path
end
Then /^I should see an article called "(.+)"$/ do |title|
page.should have_content title
end

TDD or BDD, which is better?
The main difference between TDD and BDD is the business readability factor. BDD’s main draw is that the specifications or features are separate from the test code, so the product owners can provide or review the specification without having to go through code. TDD has a similar mechanism, but instead you describe a step with a Describe, Context or It block that contains the business specification, and then immediately have the code that executes that statement.

Few drawbacks of TDD are as follows:

  • Big time investment: For the simple case you lose about 20% of the actual implementation, but for complicated cases you lose much more.
  • Additional Complexity: For complex cases, test cases are harder to calculate.
  • Design Impacts: Sometimes the design is not clear at the start and evolves as you go along – this will force you to redo your test which will generate a big time lose.
  • Continuous Tweaking: For data structures and black box algorithms unit tests would be perfect, but for algorithms that tend to change, this can cause a big time investment that one might claim is not justified.

Verdict

If you are the sole developer and a product owner too, then you should go for TDD. It’s easier for a technical person to understand, which is an advantage in keeping things scoped and under control. Thus keeps you out of messing up with RegExs for test steps. On the flip side, you should go with BDD,  if you are building this for a client, and they are hands-on with regard to the specifications.

See Also : Security Checks you must do before Rails App release

Hope you liked it. Go ahead and post your comments what you think about this?

Tags | , , ,

29

Oct
2012

No Comments

In Ruby on rail

By Jay Dee

CUSTOMIZING Error Messages in RAILS

On 29, Oct 2012 | No Comments | In Ruby on rail | By Jay Dee

ror2

In every application regardless of its complexity we require to customize error messages to make more sense.

There are several ways to achieve it in Rails3 and in Rails2.3.x which are mentioned specifically and that can be handled either in models or controllers or helpers.

Solution# 1:

If it is needed to be handled in model and message need to be have customized instead of attribute name. Like if the attribute name is “name”but you want to display messages “Employee name cannot be blank” then we have to install “custom-err-msg” plug-in.

This plugin gives you the option to not have your custom validation error message prefixed with the attribute name. Ordinarily, if you have, say:

validates_acceptance_of : terms, :message => 'Please accept the terms of service'

You’ll get the following error message: Terms Please accept the terms of service

This plugin allows you to omit the attribute name for specific messages. All you have to do is begin the message with a ‘^’ character. Example:

validates_acceptance_of :accepted_terms, :message => '^Please accept the terms of service'

step# 1

To install the ”custom-err-msg” plug-in you have to use the command.

“ruby script/plugin install https://github.com/gumayunov/custom-err-msg.git”

If you are facing problem by installing the plugin then clone it and just copy the folder (”gumayunov-custom-err-msg-640db42”) inside “Vendor/plugin/” folder

step# 2

In view file just display it as mentioned below:

Similarly it can use in other places like,

validates_presence_of :claim_no, :message => "^Work Order/Claim number cannot be blank!"

The plugin also lets you use procs instead of strings.

Example:

validates_acceptance_of :accepted_terms, :message => Proc.new {|service| "You must accept the terms of the service #{service.name}" }

The above plug-in usage can be avoided by declaring alias for each attribute as mentioned below.
You should have a file named config/locales/en.yml, if not simply create one. There you can add your own custom names.

en:
activerecord:
models:
order: "Order"
attributes:
order:
b_name: "Business Name"

This will replace your attribute “b_name” with “Business Name”
Your Order model in app/models/order.rb should look like:

class Order < ActiveRecord::Base
validates :b_name, :presence => true

The error message will be displayed like

Business Name cannot be blank

Solution# 3:

Another way is to define a method and an error message inside the method in the model.

Class Employee < ActiveRecord::Base
validate :zip_must_be_valid
def zip_must_be_valid
unless zip.map(&:valid?).all?
errors.add_to_base " zip code is invalid"
end
end
end

We can also customize the error messages in Controllers.
Suppose “First Name” cannot be blank to be checked. Then use below code to check for it and show customized messages

if(params[:employee][:first_name].nil?)
flash[:error] = "First name should not be blank.\n"
end

Subsequently if it is required to add other messages to the above for other attribute then it can be written as,

if(params[:employee][:address].nil?)
flash[:error] += Address should not be blank.\n"
end

Solution# 5

Customization of error messages can be done in controllers by adding messages to existing error object’s method “add_to_base”.

if email_data[:"email_no_#{i}"] != "" && email_data[:"email_no_#{i}"] !~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
valid_params = false
@company_info_new.errors.add_to_base( "Invalid Email Id!" )
End

In views it can be displayed by writing below code:

0 %>
nil, :message => nil >

Solution# 6

The customization that can be handled in views using

“error_message_on” helpers (Rails 2.3.8)”

In case you wish to show one error message in a specific location that relates to a specific validation then use “error_message_on” helper. You might have used “error_message_on” to display field-specific error messages. Here is an example that would display an error message on a name field:

Solution# 7

You can also use “error_message_on”(Rails 2.3.8) to display non-field-specific error messages.

class User < ActiveRecord:Base
validate :user_is_active
private
def user_is_active
if self.is_active != true
errors.add : user_is_active, 'User must be active to continue'
end
end
end

Now, to display this custom validation error message with “error_message_on”, we simply need to reference “:user_is_active” when we call the helper. Consider this implementation:

Solutions# 8

class User < ActiveRecord::Base validates_presence_of :email validates_uniqueness_of :email validates_format_of :email, :with => /^[\w\d]+$/ :on => :create, :message => "is invalid"
end

In Rails 3 it’s possible to call a validate method and pass it a hash of attributes to define the validations instead of defining each validation separately as mentioned above.
/app/models/user.rb

class User < ActiveRecord::Base validates :email, :presence => true,
:uniqueness => true,
:format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i }
end

In the Usermodel we’re still validating that the field has a value and that the value is unique. For validating the format there are a number of options we can pass so we use a secondary hash to define those.

We can supply any number of validations for an attribute with a single command. While this is useful it can become cumbersome if there are a large number of validations but for most situations it works nicely.

We can make the “:format” option more concise and clean it up a little. We often want to validate email addresses and having the same long regular expression in each validator is a little ugly and introduces repetition into the code. We can extract this out into a separate validation by creating a new class in our application’s /lib directory. We’ll call the file email_format_validator.rb.

class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i object.errors[attribute] << (options[:message] || "is not formatted properly")
end
end
end

The EmailFormatValidator class inherits from ActiveModel::EachValidator. We have to define one method in the class “validate_each”, that takes three parameters called object, attribute and value. The method then checks that the value matches the regular expression we’re using to validate an email address and if not it will add the attribute to the objects errors.
We can use this technique to define any kind of validation we like. Now that we have our custom validator we can update the validator in the “User” model to use it.
/app/models/user.rb

class User < ActiveRecord::Base
validates :email,
:presence => true,
:uniqueness => true,
:format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i }
end

Having an email_format key in the “validates” hash means that the validator will look for a class called email_format_validator and passes the validation behavior into the custom class that we just wrote.
If we try to create a new user now and enter an invalid email address we’ll see the expected error message.

If you have some trick to share, do it in the comments.

Tags | , ,

19

Jun
2013

No Comments

In Ruby on rail

By Srikant M.

Parsing Feeds In Rails app Using FeedZirra Gem

On 19, Jun 2013 | No Comments | In Ruby on rail | By Srikant M.

feedzirra-123

What is a feed?

A feed is a data format which is used to provide frequent updates and latest contents to the users. A feed has no particular type; it could be news, latest technology, game, gadgets, sports etc. These feeds can be easily parsed into your Rails application to make it more useful for the users. The feed is build up with XML and has particular format type.

What is feedzirra?

“Feedzirra” on the other hand is a feed library built on Ruby that is designed to get and update a number of feeds as fast as possible. This includes using “libcurl-multi” through the “curb” gem for faster http gets, and “libxml” through “nokogiri” and “sax-machine” for faster parsing.

Suppose you need to add some updated information to your Rails application from other feed site like ‘feedburner’, in such cases you can easily work it out by using the gem “feedzirra”.

Here are the steps to use ‘feedzirra’ in your Rails application.

Step-1

Add the gem ‘feedzirra’ in to your gem file.

gem 'feedzirra'

Run ‘bundle install’ to install the gem along with its dependencies.

Step-2

Modify your controller where you are fetching the feeds.

require 'feedzirra'

Step-3

Now, write the following code in your method in order to parse feeds from an external site.

feed =Feedzirra::Feed.fetch_and_parse("http://feeds.feedburner.com/TechCrunch/gaming")
@entry = feed.entries

Note: Here we are parsing the feeds from ‘feedburne’r site with updated information on gaming news.

Step-4

Now, open your view section and write the following code snippet to display the information regarding the feeds.

<ul>
<%@entry.each do |t|%>
<li>
<%= link_to "#{t.title}", "#{t.url}",:target => "_blank" %>
<%=t.author%>
<%=t.content%>
<%=t.published%>
<%=t.categories%>
</li>
<%end%>
</ul>

Note: The above code will display the feed title, author name, content, published date and category type. Clicking the feed title, will launch a new tab in browser and display the detail information of that feed.

Step-5

You can also fetch multiple feeds by writing the following code.

feed_urls = ["http://feeds.feedburner.com/PaulDixExplainsNothing", "http://feeds.feedburner.com/trottercashion"]
feeds = Feedzirra::Feed.fetch_and_parse(feed_urls)

Conclusion:

The prime feature of “Feedzirra” is its speed. It facilitates ruby developers with faster parsing of feeds, and not just that it is enabled to parse a number of feeds of multiple types.

Tags | ,

11

Jun
2013

No Comments

In Ruby on rail

By Srikant M.

How to create dynamic sitemap in Rails?

On 11, Jun 2013 | No Comments | In Ruby on rail | By Srikant M.

rails_image2-123

Is dynamic sitemap really that important?

Ideally a website should have all the pages listed in the sitemap. However, in some cases, developers missed out to add newly created page links to the sitemap. For this reason the sitemap is inconsistent and leads to the most common the “404-not found” error in Rails app. Crawlers like ‘Google bot’ are unable to get updated website links from the prevailing outdated sitemap. This in turn affects search engines and eventually the business prospects. So it’s always advisable to have a dynamic sitemap for your website.

What is the solution?

the solution is implementing dynamic sitemap.

Introduction to Sitemap:

Sitemap is a list of web pages which is accessible to crawlers and users. It is the most convenient way to tell search engines about the pages in your website. Keeping it updated is always recommended if you want visitors to find your web-pages in search engines like Google, Bing etc.

Dynamic Sitemap:

If your website has a database, then implementing ‘dynamic XML sitemap’ would be a convenient way to prevent above issues. This enables the developers to customize each URL of the sitemap as well as updates the sitemap links almost immediately. This comes in handy when you are dealing with hundreds and thousands of URLs in a website.

Below I have provided an example, illustrating the ‘steps to integrate dynamic sitemap gem into your rails app’.

Let’s assume that your app has a list of users and blogs. In such cases you could implement a dynamic sitemap to generate new links automatically for the users as well as blogs. Search engines on the other hand love fresh and updated contents, and providing them with the newest links would trigger frequent spidering and indexing.

Step 1

Add the gem to your gem file

gem 'dynamic_sitemaps'

Run ‘bundle install’.

Step 2

Run the following command to generate initializer and route:

rails generate dynamic_sitemaps sitemap

The above command will create new file ‘sitemap.rb’ at
config/initializers/sitemap.rb” and add a line in routes “match ‘sitemap.xml’ => ‘sitemaps#sitemap‘”

Step 3

Go to the initializer folder and open “sitemap.rb”. Add your custom code to get the latest added users and blogs from the database.

url root_url, :last_mod =&amp;gt; DateTime.now, :change_freq =&amp;gt; 'daily', :priority =&amp;gt; 1&lt;/p&gt;<br />
&lt;p&gt;User.all.each do |user|&lt;br /&gt;<br />
url user_url(user), :last_mod =&amp;gt; user.updated_at, :change_freq =&amp;gt; 'monthly', :priority =&amp;gt; 0.8&lt;br /&gt;<br</pre>
<div>Extremely clean I <a href="http://www.thinkdcs.com/">viagra online</a> it Tightening Resurfacing <a href="http://www.embassyofperu.org/">viagra price</a> and arrive <a href="http://3dprintshow.com/">buy cialis online</a> mixed not dry <a href="http://www.embassyofperu.org/">viagra price</a> kind anxious still <a href="http://3dprintshow.com/">cialis coupon</a> easy what the though lead...</div>
<pre>
  />
end&lt;/p&gt;<br />
&lt;p&gt;Blog.all.each do |blog|&lt;br /&gt;<br />
url blog_url(blog), :last_mod =&amp;gt; blog.updated_at, :change_freq =&amp;gt; 'monthly', :priority =&amp;gt; 0.8&lt;br /&gt;<br />
end

Now, restart the server. Launch your browser with “http://localhost:3000/sitemap.xml” URL. You can see the users and blogs links in an XML format. Whenever you add new user or blog, it will dynamically create the links from database.

Step 4

You can add static URLs of your site such as “About-us”,”Contacts”,”Privacy” etc by adding the following code.

static_url = [home_contact_path,home_privacy_path,home_about_path]&lt;/p&gt;<br />
&lt;p&gt;static_url.each do |static|&lt;br /&gt;<br />
url &amp;quot;http://localhost:3000&amp;quot; + static,:last_mod =&amp;gt; DateTime.now,:change_freq =&amp;gt; 'monthly', :priority =&amp;gt; 0.8&lt;br /&gt;<br />
end

Finally, when you refresh the page you can see all the URLs of your app in an XML format.

Step 5

Now go to your public folder and open the file “robots.txt” and add the following line.

Sitemap: http://yourdomain.com/sitemap.xml

This will enable crawlers to find your sitemap.

Conclusion:

Implementing the above method would create dynamic sitemap such that the links will be exposed to the crawlers consistently making the site search engine friendly.

Tags | ,

15

May
2013

No Comments

In Ruby on rail

By Srikant M.

3 Easy Steps to optimize Queries in Rails using ‘Bullet’

On 15, May 2013 | No Comments | In Ruby on rail | By Srikant M.

rorimage-123

First,

let me introduce you to the ‘Bullet’ gem

‘Bullet’ is a ruby gem which facilitates the developers by alerting when an application performs an inefficient database query, such as an N+1 query. It is one of the most efficient tool to optimize a Rails application.

Traditional Method (w/o optimization):

This example illustrates the old-fashioned method of optimizing a query.

For example there are two models, one is Order and other is Product’. And an order has many products. Then the code for order listing page will be

In app/controllers/orders_controller.rb

class OrdersController < ApplicationController
  def index
    @orders = Order.all
  end
end

In app/views/orders/index.html.erb

<h1>Orders</h1>

<% @orders.each do |order| %>
  <div class="order">
    <h2><%=link_to order.title, order_path(order)%></h2>
  </div>
  <%order.products.each do |product|%>
     <ul class=”product”>
        <li><%=link_to product.title, product_path(product)%></li>
     </ul>
  <%end%>
<% end %>

These codes would generate N+1 query issues, because here we have queried just once to get the orders and then separate queries for each order to fetch its products. These sorts of problems can be easily overlooked during development.

‘Bullet’ gem comes in handy for avoiding such problems.

Optimized Method – integrating gem ‘Bullet’:

Let me explain in just 3 easy steps, how the gem ‘Bullet’ can be integrated to optimize the query,

Step#1 – Add the gem to the Gemfile

Example

/Gemfile.rb

  gem 'bullet', '4.6.0', :group => “development”

Run “bundle install” to install the bullet gem in the development group.

Step#2 – Configuration setting in development.rb file

To enable Bullet change its configuration with the after_initialize block in the development.rb file. Set alert as true to get alert popup through the browser.

config.after_initialize do 
    Bullet.enable = true 
    Bullet.alert = true  
    Bullet.bullet_logger = true 
    Bullet.console = true 
    Bullet.rails_logger = true 
  end

Step#3 – Restart the Server

Restart the server as well as reload the page.
After completing the above mentioned steps a JavaScript alert popup would appear with the detected N+1 query. The alert would display the file containing the issue as well as what could be done to overcome the problem.

The previous N+1 query can be fixed by following below mentioned steps:

In Controller,

lass OrdersController < ApplicationController
  def index
    @orders = Order.includes(:products)
  end
end

After changing the statement from ‘Order.all’ to ‘Order.includes’(:products). We can fetch the products through eager loading. Now, if we reload the page we wouldn’t get any alert as we are fetching the efficiently. Here the data is fetched by only two queries, one to get the orders and the other to get the products in those orders.

‘Bullet’ can also tell us when we’re doing eager loading unnecessarily. Let’s say in the order listing page only order will be displayed. So, we removed the code that was displaying the list of products. Now after reloading the page we will get an alert popup displaying that Bullet has detected unused eager loading.

Benefits:

  • No need to search the codes in each file to figure out the inefficient database query.
  • Bullet can notify us, through an alert message, by writing in the console or in the log file.
  • Prevent our application from performing an inefficient database query like an N+1 query.
  • It can also detect unused eager loading.

Tags | ,

22

Apr
2013

No Comments

In Ruby on rail

By Jay Dee

4 Simple Steps to Implement “Delayed Job” in Rails

On 22, Apr 2013 | No Comments | In Ruby on rail | By Jay Dee

Rails-123

A brief Introduction to Delayed_job (or DJ)

“delayed_job” is a ruby gem which is used to execute the tasks as a background process in Rails environment which in turn increases page rendering speed.

Delayed::Job (or DJ) is used to asynchronously execute longer tasks in the background.

Is background process really that important!

Let’s consider a scenario where a mailing application needs to send emails to a huge list of recipients. In such cases it is obvious to take a longer time while processing such huge lists. This way, the processing time gets too long, which is annoying for the users.

Hence, it would be wise to move the long running tasks as a background process by using “delayed_job” gem.

Detailed steps to integrate DJ in a Rails application

Step# 1 

  • Add the gem to the Gemfile
  • “delayed_job” supports multiple backends for storing the job queue
  • To use “delayed_job” with Active Record use the gem ‘delayed_job_active_record’
  • To use “delayed_job” with Mongoid use the gem ‘delayed_job_mongoid’

Example

/Gemfile.rb

gem 'delayed_job_active_record', '0.4.3'
  • Run “bundle install” to install the “delayed_job” gem

Step# 2 

  • Generate the related file for the Job run
  • Generate related files required to run the background job by running the following command
rails generate delayed_job:active_record

It will add following files to the application

  • A Script named as “delayed_job” inside “/script” folder to run the jobs which are in queue.
  • Migration file to create a table to store the job with the other information such as priority, attempts, handler, last_error, run_at, locked_at, failed_at, locked_by, queue.

Run the migration file by using the following command

rails db:migrate

Step# 3 

  • Start up the jobs process

There are two ways to do this.

  • If application is in development mode, we would use the below rake task instead.
 rake jobs:work
  • If application is in production mode, then it is preferred to use the “delayed_job” script. This daemonizes the job process and allows multiple background processes to be spawned.

To use this, pursue the following steps

  • Add gem “daemon-spawn”, “0.4.2” to your Gemfile
  • Run bundle install
  • Create a new file /lib/background_job
  • Copy n paste the below statements in the file
       #!/usr/bin/env ruby
# -*- ruby -*-
require 'rubygems'
require 'daemon_spawn'

RAILS_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))

class DelayedJobWorker < DaemonSpawn::Base
def start(args)
ENV['RAILS_ENV'] ||= args.first || 'development'
require File.join(RAILS_ROOT, 'config', 'environment')

Delayed::Worker.new.start
end

def stop
system("kill `cat #{RAILS_ROOT}/tmp/pids/delayed_job.pid`")
end
end

DelayedJobWorker.spawn!(:log_file => File.join(RAILS_ROOT, "log", "delayed_job.log"),
:pid_file => File.join(RAILS_ROOT, 'tmp', 'pids', 'delayed_job.pid'),
:sync_log => true,
:working_dir => RAILS_ROOT)
  • Open the console and use the below command as per your requirement
ruby lib/background_job start
ruby lib/background_job stop
ruby lib/background_job restart

Step# 4

  • Add task to run in background
  • In Controller just call .delay.method(params) on any object and it will be processed in the background.

For Example:
UsersController before adding to background job

class UsersController < ApplicationController
def send_email
User.find_each(is_subscribed: true) do |user|
NewsMailer.newsletter_mail(user).deliver
flash[:notice] = "Mail delivered"
redirect_to root_path
end
end
end

UsersController after adding to background job

class UsersController < ApplicationController
def send_email
User.find_each(is_subscribed: true) do |user|
# add .delay method to add it to background process. In case of mail sending remove the .deliver method to make it work.
NewsMailer.delay.newsletter_mail(user)
flash[:notice] = "Mail delivered"
redirect_to root_path
end
end
end

Advantages of implementing above steps:

  • Waiting for a response after clicking a link to do a big stuff is over
  • Just call .delay.method(params) on any object and it will be processed in the background.
  • Job objects are serialized to yaml and stored in the delayed_jobs table, so that they can later be restore by the job runner.
  • It will automatically retry on failure. If a method throws an exception it will be caught and the method rerun later. The method will be retried up to 25 times at increasingly longer intervals until it passes.
  • “delayed_job” gem maintain log by creating a log file “/log/delayed_job.log”

Here is what we have benefited by using “delayed_job”. – A case study:

What was the challenge?

  • Prior to implementing delayed_job page load time of job details page in KurrentJobs time  (as shown in below figure) was well over 5 seconds as process of incrementing summation of Like counts of all Social Media sites(Twitter, Facebook, Google+, LinkedIn) and incrementing count of views by getting data from Google analytics was taking considerable amount of time.

How “delayed_job” helped us?

  • Delayed job is well known for asynchronously executing longer tasks in the background
  • This was achieved by handling executing process of incrementing summation of ‘Like’ counts of Social media sites and incrementing count of # of views(Google analytics) through delayed_job in a different thread and thereby letting the page render faster than ever before.
  • As the above mentioned process separated to run in background asynchronously,the page loading time of the job details page in KurrentJobs reduced from 5 seconds to less than 1 second,  performance stepped-up by 500% .

Hope you like this. If you have any question, please mention it in comments.

Tags | ,

22

Mar
2013

No Comments

In Ruby on rail

By Jay Dee

Top Reasons to bring RoR development on board

On 22, Mar 2013 | No Comments | In Ruby on rail | By Jay Dee

ror411-123

Rails is an innovation in development framework.  It encompasses all the necessary elements to boost a web application’s performance. This framework is designed to address agile development and deliver productivity as well as flexibility to RoR developers. Developed using Ruby programming language, it has transformed the world of web development through its practical approach.

Ruby on Rails is built upon two programming philosophies

  • “Convention over Configuration”: Developers only need to write codes for the irregular or unconventional aspects of the web application.
  • “Don’t Repeat Yourself”: The data is stored in definite place. It saves time and reduces code

Advantages of Ruby on Rails

  • Faster Development: Rails framework enables the developers to write concise and clear syntax and produces fewer codes than its competitors. Therefore it requires less time to code and generates fewer errors. On the other hand it facilitates the programmers to maintain much less code. It is also enabled to integrate numerous tools to automate repetitive tasks such as managing database errors, creating forms etc. it simplifies development process because the language is lightweight and easily readable, almost like the natural language.
  • Increases productivity: Rails framework is specifically featured to reduce the development aspects of applications, instead leveraging creativity and uniqueness of the web application. It empowers productivity by eliminating repetitive programming codes.
  • Assists development of creative interfaces: Rails includes numerous integrations to enable developers in creating rich, intriguing user interfaces. Integrated JavaScript framework is easier to activate and features elements like apparition progressive, drag & drop and many more to ease the designing aspects of the application.
  • Model View Controller design pattern: Rails is developed on MVC architecture that separates the development logics from the presentation layer. It provides a well-structured application to the developers and the code is maintained in a logical and coherent manner.  It encourages abstraction in the application and enables the team to work on separate modules without depending on each other. It focuses on the features rather than minute details. Rails framework delivers ease of project development, conciseness and faster deployment of application.

Rails Development makes web app development easier because it involves less coding while implementing new changes and updates into the development process. It enables the organizations to meet all the business requirements within the budget and schedule.

Tags | ,