Skip to main content

Posts

Showing posts from March, 2014

Setting Up a Cloudfront CDN for Rails

Setting Up a Cloudfront CDN for Rails? Implementing a CDN to serve compiled assets in Rails is one of the most significant performance enhancements I’ve seen. Having done so for 2 fairly large applications, it’s hard for me to imagine serving assets locally anymore. The Asset Pipeline The addition of the Rails asset pipeline has reduced both the number of assets served and the size of these files. Users on slow connections have been the biggest beneficiary of these changes. The Problem Even with the asset pipeline, content is transmitted to the end user over their, sometimes slow, connection. Distance plays a role in the speed at which data can be delivered. Because of this, users further away from your servers get a sluggish experience. This decreases both the users’ patience and your ability to effectively engage them. The Solution CDNs are networks of servers that host your content so that when you make a request, the request is served from a server closest to you. This can often...

Caching in Rails with memcached?

Caching in Rails with memcached ? Installation 1. Follow this link to download and install memcached. 2. Start the memcached server using either memcached -vv or /etc/init.d/memcached start Integrating memcached with your rails application. 1. Install memcache-client gem install memcache-client 2. Add the below line to  end of your config/environment.rb file. CACHE = MemCache.new('127.0.0.1') 3. Add the following method to your application controller / application helper or where ever you want according to your need. def perform_cache(key)   begin    unless output = CACHE.get(key)      output = yield      CACHE.set(key, output, 15.minutes)    end  rescue => e   logger.info “MEMCACHE ERROR++++++++++++++++++++++++++++++++++++”   logger.info “ERROR : #{e.message}”   logger.info “MEMCACHE ERROR++++++++++++++++++++++++++++++++++++”   output = yield   en...

How to Install and Use Edge Rails?

How to Install and Use Edge Rails? 1.  If you want to freeze your application to the gems version currently available on your system, then go to root of your rails application and run rake rails:freeze:gems By running the above command a new directory “rails” will be created inside your vendors directory. When you run your rails framework, Your application will first check for this directory and if it’s present, Rails components will be loaded from this directory instead of using your system copy of rails, and thus you are switched from Gems Rails to Edge Rails. 2.  If at any point of time, you want to switch back from Edge Rails to Gem Rails. You can always do it by running the below command rake rails:unfreeze 3. If you want to freeze your application to the latest development version, then run. rake rails:freeze:edge once you are switched to the latest development version, your javascripts and other configuration files needs to be updated corresponding to ...

Edge Rails ?

Edge Rails ? Before you get to know how to install and use Edge Rails, you need to know what actually Edge Rails is. Edge Rails actually means running a local developmental version of rails. It’s an alternative to gem rails. Many a times I have thought how to freeze my rails application to local gems version or a particular gems version, So that I can run my frozen application on some other system which have some different version of rails installed. Luckily I found Edge Rails. For example:- Consider you have frozen your rails application to the latest rails version 2.3.2 and you want to run this application on a different system which have a much older version of rails, consider for example version 2.1.0. In this case you can run your newest frozen version of rails application on  other system, which have an older version of rails installed, without any glitches or bugs, using Edge Rails.

Rails crontab with “whenever” gem ?

Rails crontab with “whenever” gem ? Introduction gem “whenever“  provides you with the valid cronjob syntax and also writes / updates the crontab file for you. Installation 1.  Install the gem gem install whenever 2. Add below line to your config/environment.rb config.gem ‘whenever’, :lib=>false, :source=>’http://gemcutter.org’ 3.  Go to your application root directory and run the below command wheneverize .    This will create a “config/schedule.rb” file for you.   EXAMPLE “config/schedule.rb”   set :environment, :development   set :path, "/var/www/MyApp"   # Scheduled Hourly    every 4.hours do    command "/usr/bin/your_command"    end   # Scheduled Daily    every 1.day, :at => '12:00 am' do    runner "MyModel.yourmethod"    end    # Scheduled Weekly    every :monday, :at => '11:00 pm' do    rake   "your:rake:ta...

Active Scaffold : Add radio buttons to your form ruby on rails ?

Active Scaffold : Add radio buttons to your form ruby on rails ? The way to add radio buttons to your active scaffold create/update from is as shown below #Controller class UsersController < ApplicationController active_scaffold :user do |config| config.label = “Users” config.columns = [:name, :gender] config.columns[:gender].form_ui = :radio config.columns[:gender].options[:options] = [['Male', '1'], ['Female','2']] end end

Active Scaffold : Add checkbox array for a particular field in rails?

Active Scaffold : Add checkbox array for a particular field in rails? Suppose you have a field in your table, which accepts array of values through multiple checkboxes, then here is a way to show these checkboxes on your active scaffold create/update form. #Controller class UsersController < ApplicationController active_scaffold :user do |config| config.label = “Users” config.columns = [:name,  :gender, :checklist ] config.columns[:gender].form_ui = :radio config.columns[:gender].options[:options] = [['Male', '1'], ['Female','2']] end end Assume ‘checklist’ is the column which accepts an array of values, then add the below chunk of code to your users helper #Users helper module UsersHelper def checklist_form_column(record, options) html = ‘ ‘ (1..5).each do |val| html << check_box_tag(“record[checklist][]“, val, :id => “check_#{val}”) html << “<label for=’check_#{val}’>” html << “lable_#{val}” html...

What’s new in rails 4.0?

What’s new in rails 4.0 ? Strong Parameters Mass assignment restriction has been moved from model to controller level. Ealier we used attr_accessible and attr_protected methods in model for mass assignment security, These are been removed and moved to the protected_attributes gem. In the new implementation, passing params directly to the mass assignment methods like create will raise a ActiveModel::ForbiddenAttributesError, instead of passing params directly to the create method in the controller, we pass a private method which permits the accessible attributes. class PeopleController < ActionController::Base    # Using “Person.create(params[:person])” would raise an    # ActiveModel::ForbiddenAttributes exception because it’d    # be using mass assignment without an explicit permit step.    # This is the recommended form:    def create      Person.create(person_params)    end   # T...

Posting xml data to url not in the browser for Ezpprints in Rails

Rails Posting xml data to url not the browser? ##Add this one require 'net/https' require 'rexml/document' ##Posting xml data to url in rails xml = xml = "<?xml version='1.0' encoding='UTF-8'?>         <user>          <firstname>#{@user.first_name}</firstname>          <address1>#{@user.address}</address1>          <city>#{@user.city}</city>          <state>#{@user.state}</state>          <zip>#{@user.zip}</zip>          <countrycode>#{@user.country}</countrycode>          <phone>#{@user.phone}</phone>         </user>" http://...

Basic svn commands with examples

Basic svn commands with examples ? In this tutorial, we will learn basic svn commands like svn commit, svn checkout, svn copy, svn merge, svn status, svn delete, svn merge, svn log etc that are extremely useful. And how these commands are used with proper example. What is SVN? SVN means subversion. SVN is free version control system built by Apache foundation. Subversion helps you maintaining versions of your codebase in common central repository. SVN also helps in simultaneous code development giving features like trunk, branches, tags etc. Basic SVN Commands: 1. Create a Branch svn copy trunk-url branch-url This will create branch from the trunk url given to the branch url specified in the command in your repository 2. Check-out a branch svn checkout branch-url or svn co branch-url This will check out the branch at branch-url in present working directory from which command is invoked Following operations need to be performed in a svn checked-out directory. Because these are svn di...

SVN command to check modified files rails

SVN command to check modified files ? While using SVN command line, you may need to see status codes of modified/changes files. In this tutorial we will learn SVN command to check modified files. SVN is version control system by Apache Foundation. As you have made changes in the local working copy, it may differ from repository copy of your codebase in many aspects. You can check Basic SVN commands article for understanding basic commands. The status code of a particular file can be any of following, Status     Description A     The file is being scheduled for addition in SVN repository D     The file is being scheduled for deletion in SVN repository M     The file is modified than file present in the SVN repository C     The file is in conflicted state ?     The file is not under SVN repository !     The file is missing. Moved or deleted unknown to SVN (without the use of SVN) Ab...

MySQL server start, stop or restart on MAC (lion)

MySQL server start, stop or restart on MAC (lion) ? How to start, stop, restart MySQL server on your MAC machine? mysql server start, mysql server stop and mysql server restart are three basic things that you will require during development of your project with MySQL server dependency. When working with MySQL for your Ruby on Rails as a database, many a times you have to start your MySQL server to establish database connection with your Rails Project. You have to follow command listed below to start, stop or restart MySQL server. 1: Start MySQL Server Command to Start MySQL server i.e. mysql server start using command line : $ mysql.server start OR $ mysqld => Starting MySQL SUCCESS! Above message will be displayed on successful start up of MySQL server. 2: Stop MySQL Server Command to Stop MySQL server i.e. mysql server stop using command line: $ mysql.server stop => Shutting down MySQL . SUCCESS! Above message will be displayed on successful shut down of MySQL server. 3: Res...

Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’ (2)

Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock’  (2) ? Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) or /tmp/mysql.sock doesn't exist You might have came across this error when you tried development of Ruby on Rails project with MySQL as your development database. What is the Error '/tmp/mysql.sock'? This file is required for your application to get connected to your MySQL database. Basically Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) this error can come when your MySQL server is not started. You can start you MySQL server by using following command: Command to start MySQL Server mysql.server start This will start your MySQL server and it will create the file'/tmp/mysql.sock' which is required for your application to get connected to the MySQL server. The output after you hit enter by above command is: Starting MySQL .≈ SUCCESS! which indicates successful star...

Speed up rails development environment mode

Speed up rails development environment mode ? While Running Ruby on Rails projects in development mode, many of you might have came across slow development process. Now, there is one easy way to speed up Rails Development Environment mode. You have to follow these steps to make development faster, Speed up rails development environment Step 1 Install gem named 'active_reload' on your machine. Step 2 Command to install 'active_reload' gem on your machine, gem install active_reload Step 3 After installing this gem, add the gem in your Rails Project. Step 4 To add the gem in your project file, open gemfile and add, gem 'active_reload' Step 5 Run your project in development mode This will make the development faster than what you have tried before. Basically this tool reloads the content of your web only if it detects change in the code than previous load. If you want to know more about the gem 'active_reload' then you can get it here. So, in this tutoria...

How to install ruby on MAC

How to install ruby on MAC ? Whenever you start the development of Ruby on Rails on MAC, the initial step is to install Ruby on Rails. You will learn how to install ruby on rails on MAC with this article. Steps on how to install ruby on MAC and Important Commands useful for Ruby Developer: 1.  First of all you need to have RVM installed on your machine. 2.  Then use RVM to install Ruby on your machine by following command:     rvm install ruby Above command will install the latest stable version of Ruby on your machine. 3. Install a specific version of Ruby:     - You can install specific version of ruby using following command:  > rvm install 1.9.2  => This will install ruby's stable version of 1.9.2 release > rvm install 2.0.0  => This will install ruby's stable version of 2.0.0 release 4. How to check version of Ruby installed on your machine?     - You can use ruby --version command to check the ve...

What is gemfile.lock in rails?

What is gemfile.lock in rails? What is Gemfile.lock? or What is the difference between Gemfile and Gemfile.lock? these are the common questions that you come across while starting development with Rails project. What is Gemfile?     Gemfile is the file in which you can mention which gems (kind of Third Party libraries) that you want to use for your Rails application     Gemfile lists the gems that you want to use for your development     Syntax:         gem ‘rails'             This mentions that gem with name ‘rails’ has to be used in Project context     Whenever you bundle install, then bundler finds the gems listed in the Gemfile and it installs latest stable version for the gems listed in the Gemfile     You can specify which version to be used for the rails development:         gem 'r...

Lazy loading in rails – Rails Feature

 Lazy loading in rails – Rails Feature ? Lazy loading in rails is the amazing feature provided with rails. In console you might have tried to examine how lazy loading in rails actually works. In this tutorial, we will learn about this Rails - Lazy loading feature with examples. What exactly is Lazy Loading? As the name suggests the data is loaded in lazy manner (Really!) i.e. Your database is queried only when data from the database is required for some kind of manipulation in code. You will get more of this after you read how-to of lazy loading below. How lazy loading works: Whenever you try to get some data from database, For example, users is the database table that you have. And you are querying database to get users having age less than 20. Then, you will write code like, result = User.where("age < 20") when above statement is executed, your database is not queries yet(because the resultant data is not required yet). When you execute following code, records = resu...

Concatenate Strings – How to?

Concatenate Strings  in Rails – How to? There are many ways (Ruby's Property) of concatenating Strings in Ruby. Before proceeding let us see how to create a simple String in Ruby. You can create a  String in Ruby as follows, > s1 = "ruby in rails is awesome." Let us create one more string i.e. > s2 = "And This post is really very informative" Now, you can concatenate these two strings by, > s3 = s1 + s2 This will concatenate String s1 and String s2 and give the result as, s3 will be => "ruby in rails is awesome.And This post is really very informative" I you are thinking of concatenating string with variables in between, like > year = 2013 > s = "This is 2013" Then, String s can be generated using variable a as, > s = "This is #{year}" The method used in above statement is called as "String Interpolating" in Ruby. You can use simple insertion (<<) operator of Ruby ...

uncaught exception address already in use bind(2) in rails

uncaught exception address already in use bind(2) ? You might came across uncaught exception address already in use bind(2) error while trying to start TCP Server for starting your Rails Application. We will see why Address already in use error is thrown by programs while execution. This is most common error that you will come across while developing Rails Application and solution for this is very simple. Root Cause Basically the error is self explanatory. It means that server is already started and you are trying to start it again or the some other application is already running on the specific port on TCP server. Thus your program is not able to gain access to that specific port on TCP server. Finding Process which Process is running We can find which process is using the address which Rails app tries to run on by using following command: lsof -i tcp:3000 The above command basically finds process which is using TCP server and 3000 as port address. The result of above process will ...

How to install or uninstall a gem in Ruby

How to install or uninstall a gem in Ruby ? When you start with Ruby or Ruby on Rails development, first thing that you will start-up with is Installing Gems on your machine. In Ruby, you have to install a gem so that you can use the readily available, implemented code for your purpose. How to Install a gem: You can install gem using gem command. Example of using gem command: gem install rake This will install gem 'rake' on your machine. While installing a gem you can also specify, which version of gem you have to install. Install Specific Version of Gem: gem install rake -v 0.8.7 After your gem is installed on your machine, it also install the documentation for the gem that you have installed. You can view the documentation for your installed gem with command: View Documentation of the Gem : ri rake Search the gem with name: You can search for available gems by the name using command like, gem search ^rake It will search for the gem's having name starting with 'ra...

Ruby Count vs Length vs Size

Ruby Count vs Length vs Size ? Ruby Count vs Length vs Size - These methods are used on Arrays, Hashes or Objects. This tutorial will illustrate difference between count length and size. 1. Array#length    Basically length method used on arrays in ruby returns number of elements in the array for which method is invoked. Example, suppose we have array a as, a = [1,2,3,4,5,6,7] Calling Array#length method on array will give result as, a.length => 7 For more reference on how length is calculated, refer source code for the length on apidock for Array#length which shows that it uses RARRAY_LEN(array) method to get length. 2. Array#size Array#size is just an alias to the Array#length method. It executes same Array#length method internally. Example, b = [1,2,3,4] b.size => 4 3. Array#count Count has some more functionalities than length/size. It can be used for getting number of elements based on some condition. Count can be called in three ways: Sr. No.    ...

Ruby get file extension from string

Ruby Get File Extension from String Sometimes developer requires to extract only file extension from the string object. File class can be used to perform this operation. We will see how to use File class to get the extension name. Let's create a sample string with Filename. Suppose we have a file with name "ruby-in-rails-logo.jpg" and string object as, filename = "ruby-in-rails-logo.jpg" of which extension ".jpg" we want for some check in the program. Then we can use File class as follows, Solution Use method File.extname as follows, Syntax: file_extension = File.extname(filename) => ".jpg" Method File#extname when passed string with filename then it returns extension of that file. In above example it is .jpg You can read source page of File#extname on APIDock for the C source code of this method. Sample Conversions File.extname("ruby/in/rails/logo.jpg") => ".jpg" File.extname("ruby-in-rails-logo") => ...

What is attr_accessor in Rails?

What is attr_accessor in Rails? attr_accessor is used to define an attribute for object of Model which is not mapped with any column in database. This answers question - What is attr_accessor in Rails. 1. attr_accessor Methods attr_accessor creates two methods i.e. getter method and setter method. getter method - it is used to retrieve value of the attribute setter method - it is used to set value to the attribute When to use attr_accessor in Rails? Whenever you want to show certain attribute for particular form but you do not want to store it's value in the database then you use attr_accessor for that model as follows, Suppose we have a Model called user in out database with following fields,     id     name     age     city     profession And we define attr_accessor :type_of_user as follows, Class User < ActiveRecord::Base    attr_accessor :type_of_user...

database.yml rails

database.yml rails ? Database.yml is one of the most important files in rails project, database.yml rails is actualy a configuration file. What is Contains? Database.yml is configuration file which tells rails about database, database information such as 1. database host/machine 2. which database to choose ( mySQL, Oracle, Sqlite... etc) 3. Username 4. password . There are such multiple configurations here in this file. You need to write appropriate values in this configuration based on the Database you are using, and host/machine of the DB. If you want to use MySQL Database.yml : development: adapter: mysql2 encoding: utf8 reconnect: true database: [DB name] pool: 5 username: [your username] password: [your password] host: [host name] Now If you are a java programmer, you might land up with a question in your mind that what about the drivers/connectors required. In java we need JAR files depending upon the database we are using.Rails will automatically detect the drivers based on ...

Rails RecordNotFound Exception Handling

Rails RecordNotFound Exception Handling ? Rails RecordNotFound exception occurs when there is error while fetching records from database. RecordNotFound is one of the Exception Handling class provided by Rails. 1. What is RecordNotFound Exception: It is Exception class defined in the ~/.rvm/gems/ruby-version/gems/activerecord-version/lib/active_record/errors.rb errors.rb file which comes with your Rails. 2. When RecordNotFound Exception is thrown: Code Snippet of file errors.rb mentioned above - # Raised when Active Record cannot find record by given id or set of ids. class RecordNotFound < ActiveRecordError ActiveRecordError class is inherited from StandardError class which is subclass of Exception class. Thus ultimately Exception is superclass of StandardError class. Sample code to reproduce the exception: Suppose you have users table in your database, thus model User in codebase. And you try to fetch record by following code: User.find(1234352) And your database don't ha...

Rails NameError uninitialized constant class solution

Rails NameError uninitialized constant class solution ? rails nameerror uninitialized constant class will occur if your rails console is not loaded with configuration of the class file containing method being called. Problem Basically this can happen if you happened to call the function from the class which is not loaded with configuration when your rails console/server was started. Example Suppose you create a file named Util.rb in the lib folder of your Rails project. Class Util    def self.get_date     Time.now.strftime(‘%F’)    end end And then if you want to call the function through command line i.e. rails console probably you will start rails console and and call the method get_date using class name Util as follows, rails console > Util.get_date This will give you following error - NameError: uninitialized constant Util It means that your class was not loaded when the rails console was started Solution To resolve this problem your class h...

ActiveRecord Attributes – access using Strings, Symbols and Direct Access rails

ActiveRecord Attributes – access using Strings, Symbols and Direct Access rails ? Attributes can be accessed from ActiveRecord in various ways including symbolised, stringified or direct access. Each type of access has it’s own advantages and disadvantages as we will see in this tutorial. Sample Table for use case - Suppose we have a table users in database. Table Name: users id     name     city 1     Abcd     NewYork 2     Efgh     PolaAnd Suppose, we want to have record of user with id = 21. Then we can get the details of this record using rails as, user_details = User.where('id = 1').first Now we will see different types of access over the active record user_details 1. Direct Access Let us say we want to access name attribute of user from the ActiveRecord user_details. This can be obtained using direct access as follows, name = user_details.name puts "Name of the User is #{name}" => Abcd...

How to integrate Twitter Bootstrap Rails with Rails

How to integrate Twitter Bootstrap Rails with Rails ? How to Integrate Twitter Bootstrap Rails with Rails project is the First question that developers have to face before starting a new project. It can be done using Gem twitter-bootstrap-rails or manually. What is Twitter Bootstrap? Twitter Bootstrap is popular open source CSS, JS framework used for beautifying your Web Application. It was built at Twitter by Mark Otto and Jacob Thornton to have consistency of UI for their tools. The tool became so popular that it is now being used by many developers as the framework for their web world Option 1 - Using twitter-bootstrap-rails Gem: Twitter Bootstrap can be integrated with Rails using twitter-bootstrap-rails using following steps. Step 1. Add gem 'twitter-bootstrap-rails' to your Gemfile like this. group :assets do    gem 'twitter-bootstrap-rails' end Step 2. Run following command in your Rails application directory bundle install This will install twitter-bootstra...

Rails Migration Difference between Text and String

Rails Migration Difference between Text and String ? While working with Rails Migration Difference between Text and String is important to be known to every developer. Columns and their data types are finalized while deciding Table structure. This tutorial will help understand difference between String and Text column type and illustrate how to write Rails Migration implementing the same. You might want to read about database.yml files for specifying database configuration for Rails Application. 1. Concepts When String or Text data type is required?     Whenever you require your column to store information which is lengthy in size (Many characters), you need to consider String or Text data type for the column.     Both of them let you store Many(How Many - will see later) characters Difference between String and Text Considering MySQL database Feature     String     Text Length     1 to 255     ...

How to integrate Semantic UI Rails with Rails App

How to integrate Semantic UI Rails with Rails App ? Semantic UI is the new popular CSS, JS framework for beautifying your Website. Tutorial will help understand how to integrate Semantic UI with Rails application and how to test the sample Semantic UI components with your Rails application. What is Semantic UI According to Semantic UI - Semantic empowers designers and developers by creating a language for sharing UI. If you are looking for CSS, JS framework other than Twitter Bootstrap or Foundation then Semantic UI is the best option to try out. There are 2 ways of Integrating Semantic UI with Rails Application: The one is using Semantic UI Rails and the other is Manually. Option 1. Using gem 'semantic-ui-rails' Step 1 Let us create new Rails project using command, rails new semanticTest This will create new Rails project to begin with. Step 2 Add gem 'semantic-ui-rails' gem to your Gemfile in your Rails app. gem 'semantic-ui-rails' Step 3 Perform bundle ...

Difference between Array Push and Array Insert

Difference between Array Push and Array Insert ? As we all know there are more than one way of doing the same thing in the Ruby. Thus, it becomes more important to choose the right way so that it does not affect your Performance Now, let us discuss about Arrays in Ruby. => Array is collection of entities => Array can be the collection of different type of objects like, integers, strings, hashes, symbols etc. => Methods: There are many inbuilt methods that come in handy for doing particular task => One can create Array and get list of the methods that can be called on Array object in Ruby by following command, Creating Empty Array array = Array.new   # where array is name of object Listing Methods on Array array.methods.sort # where array is object of Array class => Explore the various methods on Array class. => You can refer documentation of Ruby Array here. Array Push and Array Insert array = []   # Another way of creating an Array => We can...

Ruby – Difference between Symbols and Strings

Ruby – Difference between Symbols and Strings ? Ruby has Symbols as well as Strings. Their are differences between the two that should be known for proper use in your Application while coding. Symbols: First of all, let us take a look at how Symbols are created: > a = :First_Symbol The above statement after execution, will create object of Symbol Class. Let us create one more symbol, say b > b = :Second_Symbol This will again create object of string class. If we create another symbol, say c, like > c = :First_Symbol The, if we see their object id's: > a.object_id => 5304108 > b.object_id => 5305708 > c.object_id => 5304108 You must have observed, the object id's of Symbol a and Symbol c are one and the same. i.e. 5304108 It shows that if symbol with the same name already exists in the memory then the same reference is given to the new object with the same name. i.e. Multiple Symbol objects with the same name will have same reference. Strings: First...

Ruby – Difference between Require and Include

Ruby – Difference between Require and Include ? While coding with Ruby or Ruby on Rails, you might have came across Require and Include. There are quite a few differences between Require and Include. First of all let us see, what Require does in Ruby. 1. REQUIRE Syntax: require(name) Returns: boolean (true/false) Action The name which is passed as parameter to the require, ruby will try to find the source file with that name in your load path. What is load path? The load path is the path from where library files for your program are loaded. You can see what is the load path for your programs by the following command. > $load_path This will list the load path i.e. locations from where library files are loaded. If name which is passed as argument includes extension .rb then ruby will try to find the file with the same name and extension in the load path, otherwise i.e. If you do not provide the extension for the name then ruby will try to find the file with same name with .rb as ...

How to Check if value is included in between the range in rails ?

How to Check if value is included in between the range in rails ? There are many ways of doing the same thing in Ruby. How to check if a number is between the two values? Available Methods You can check if value is in the range by use of following methods, between member include These methods can be implemented as follows, Let us initialize three numbers as follows, Sample Usage a, b, c = 10,14,20 b.between?(a,c) # returns true/false. here true (a..c).member?(b) # returns true/false. here true (a..c).include?(b) # returns true/false. here true But, I would suggest using between? than member? or include? The reason behind preferring between that other two is Performance, Benchmark Performance Suppose, we measure their Benchmarking performance as follows, Benchmark.bmbm do |x| x.report { 100000000.times{ 14.between?(10,20)}} x.report{ 100000000.times{(10..20).member?(14)}} x.report{ 100000000.times{(10..20).include?(14)}} end #resultRehearsal ------------------------------------ 14.0...

strftime – Format Date Time in Ruby

strftime – Format Date Time in Ruby ? In Ruby, you have to format or convert time from one format to other many a times. You can use library method strftime available to perform formatting operations. Syntax of strftime: strftime( format ) Returns: Result in requested format First of all, let us create a new variable in which we get current time to be formatted in various formats, t = Time.now => 2013-09-12 22:49:27 +0530 Now, we have variable t holding current time value, now below are the examples of, Most Commonly used formats Code     Output     Description t.strftime("%H")     => "22"     # Gives Hour of the time in 24 hour clock format t.strftime("%I")     => "10"     # Gives Hour of the time in 12 hour clock format t.strftime("%M")     => "49"     # Gives Minutes of the time t.strftime("%S")     => "27"     # Giv...

Benchmark in Ruby code using bm and bmbm with examples

Benchmark in Ruby code using bm and bmbm with examples ? In Ruby, you have to perform benchmarking to measure performance of your code. Ruby allows you to do Benchmarking using library called 'benchmark' You have to include library before you start with Benchmarking. Let us see example of how you can perform benchmarking in Ruby. require 'benchmark' It will allow you to use Benchmark library. Now, suppose you have two code blocks which you have to compare, Let us say we have array a and b, > a = [] > b = [] Now, you have to push the element 5 into these arrays. Let's perform this operation 1000000 times so that it will take significant amount of time by which we can compare these two operations or code blocks. Code block 1: 1000000.times{ a=[]; a << 5} Code block 2: 1000000.times{ b=[]; a.push(5)} 1. Benchmark bm method Benchmark.bm do |performance| performance.report("Insert"){ 1000000.times{ a=[]; a << 5}} performance.report("Pu...