Wednesday, August 5, 2015

Rake is a utility similar to make in Unix. You can say Rake is the make of ruby - the R uby m AKE. Rails defines a number of tasks to help you.
Here is a list of various important commands supported by Rake:

  • rake db:fixtures:load - Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y
  • rake db:migrate - Migrate the database through scripts in db/migrate. Target specific version with VERSION=x
  • rake db:schema:dump - Create a db/schema.rb file that can be portably used against any DB supported by AR.
  • rake db:schema:load - Load a schema.rb file into the database.
  • rake db:sessions:clear - Clear the sessions table.
  • rake db:sessions:create - Creates a sessions table for use with CGI::Session::ActiveRecordStore.
  • rake db:structure:dump - Dump the database structure to a SQL file.
  • rake db:test:clone - Recreate the test database from the current environment's database schema.
  • rake db:test:clone_structure - Recreate the test databases from the development structure.
  • rake db:test:prepare - Prepare the test database and load the schema.
  • rake db:test:purge - Empty the test database.
  • rake doc:appBuild the app HTML Files.
  • rake doc:clobber_app - Remove rdoc products.
  • rake doc:clobber_plugins - Remove plugin documentation.
  • rake doc:clobber_rails Remove rdoc products.
  • rake doc:plugins - Generate documation for all installed plugins.
  • rake doc:rails - Build the rails HTML Files.
  • rake doc:reapp - Force a rebuild of the RDOC files
  • rake doc:rerails - Force a rebuild of the RDOC files
  • rake log:clear - Truncates all *.log files in log/ to zero bytes
  • rake rails:freeze:edge - Lock this application to latest Edge Rails. Lock a specific revision with REVISION=X.
  • rake rails:freeze:gems - Lock this application to the current gems (by unpacking them into vendor/rails)
  • rake rails:unfreeze - Unlock this application from freeze of gems or edge and return to a fluid use of system gems
  • rake rails:update - Update both scripts and public/javascripts from Rails.
  • rake rails:update:javascripts - Update your javascripts from your current rails install.
  • rake rails:update:scripts - Add new scripts to the application script/ directory.
  • rake stats - Report code statistics (KLOCs, etc) from the application.
  • rake test - Test all units and functionals
  • rake test:functionals - Run tests for functionalsdb:test:prepare
  • rake test:integration - Run tests for integrationdb:test:prepare
  • rake test:plugins - Run tests for pluginsenvironment
  • rake test:recent - Run tests for recentdb:test:prepare
  • rake test:uncommitted - Run tests for uncommitteddb:test:prepare
  • rake test:units - Run tests for unitsdb:test:prepare
  • rake tmp:cache:clear - Clears all files and directories in tmp/cache
  • rake tmp:clear - Clear session, cache, and socket files from tmp/
  • rake tmp:create - Creates tmp directories for sessions, cache, and sockets
  • rake tmp:sessions:clear - Clears all files in tmp/sessions
  • rake tmp:sockets:clear - Clears all ruby_sess.* files in tmp/sessions

Wednesday, June 10, 2015

How to get the current timezone with Javascript

Please include these cdns into your HTML document.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js"></script>

Invoke the script by calling:

> var timezone = jstz.determine();
> timezone.name();
"Asia/Kolkata"

Tuesday, June 2, 2015

Difference between to_s and inspect in Ruby

While running a script in Ruby, we usually want to log data from objects for debugging purpose. puts, p, logger methods are used to log along with to_s, inspect methods to log object. This tutorial will give brief about each method and when to use which one.


1. to_s

to_s is very common method used by Ruby programmers to get String representation of object on which it is called. For example,
considering fixnum,

12345.to_s => '12345'

Similarly if you try to use to_s method on Model/ActiveRecord object in Rails, it will give something like,

User.first.to_s
#<User:0x007fd15cc57238>

Which is object's representation in string. User: Class name, 0x007fd15cc57238: based on object id.

Using String Interpolation:
Whenever you use String Interpolation, Ruby calls by default to_s method on objects used in the String interpolation before printing output. For example,

user = User.first
puts "This is #{user} information"
"This is #<User:0x007fefb2002428> information"

This show that while processing string interpolation user object is converted to to_s internally.

2. inspect

inspect method is more of a developer-friendly version of to_s. For Model/ActiveRecord you can check out definition of inspect on APIDock
Considering same example as above,

user = User.first
puts "This is #{user.inspect} information"
This is #<User id: 1, email: "username@example.com", encrypted_password: "$2a$10$D57y73Q9HUXG9Hym3bLl8.MizOdTRxd6NQH6snHi4Q....", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: "2014-10-15 11:19:09", sign_in_count: 13, current_sign_in_at: "2014-10-21 20:10:18", last_sign_in_at: "2014-10-20 17:37:27", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2014-06-30 17:41:06", updated_at: "2014-10-21 20:10:18"> information"

This clearly depicts how much useful inspect is instead of to_s on objects for logging and debugging purposes.

3. p vs puts

When you use puts for printing, then puts internally uses to_s on objects before processing inputs, while p uses inspect on objects before processing inputs.
E.g. Again considering same example,

user = User.first
puts user
#<User:0x007fefb0c690b0>

This just has converted object's reference using to_s
Now tryng with p

p user
#<User id: 1, email: "username@example.com", encrypted_password: "$2a$10$D57y73Q9HUXG9Hym3bLl8.MizOdTRxd6NQH6snHi4Q....", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: "2014-10-15 11:19:09", sign_in_count: 13, current_sign_in_at: "2014-10-21 20:10:18", last_sign_in_at: "2014-10-20 17:37:27", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2014-06-30 17:41:06", updated_at: "2014-10-21 20:10:18">

Thus, you may prefer using p instead of to_s if you are looking purely for logging/ debugging purposes. Otherwise use of these methods purely depends on the required functionality though. 

Wednesday, May 20, 2015

Deprecated Finders With Rails 4

Rails 4 deprecates the old-style finder option hashes, as well as all dynamic finder methods (with the exception of find_by_... and find_by_...). Instead, you'll use where:

  • find_all_by_... can be rewritten using where(...).
  • find_last_by_... can be rewritten using where(...).last.
  • scoped_by_... can be rewritten using where(...).
  • find_or_initialize_by_... can be rewritten using where(...).first_or_initialize.
  • find_or_create_by_... can be rewritten using find_or_create_by(...) or where(...).first_or_create.
  • find_or_create_by_...! can be rewritten using find_or_create_by!(...) or 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.

Accessing helper modules into decorate with Rails 4

Additionally, a decorator has access to Rails helper modules via the helper proxy method. This is useful when you want to hide complex logic from the templates.

class PersonDecorator < Draper::Decorator
  delegate_all

  def author_headline
    if author == helper.current_user
      h.content_tag(:h3, 'You')
    else
      h.content_tag(:h3, author.name)
    end
  end
end

Now in your template you just call @person.author_headline and you are done. No conditions in the template. Your designers will be thankful!

Access current_user into decorate like below.

h.current_user

Friday, May 15, 2015

Custom Flash Types In Rails 4

This small feature may help clean up some code. You can register your own flash types to use in redirect_to calls and in templates. For example:

# app/controllers/application_controller.rb
class ApplicationController
  add_flash_types :error, :catastrophe
end
 
# app/controllers/things_controller.rb
class ThingsController < ApplicationController
  def create
    # ... create a thing
  rescue Error => e
    redirect_to some_path, :error => e.message
  rescue Catastrophe => e
    redirect_to another_path, :catastrophe => e.message
  end
end
 
# app/views/layouts/application.html.erb
<div class="error"><%= error %></div>
<div class="catastrophe"><%= catastrophe %></div>




Thursday, May 14, 2015

Renamed Callbacks in Rails 4

Action callbacks in controllers have been renamed from *_filter to *_action.
For example:

class UsersController < ApplicationController
  before_action :set_user, :except => [:index, :new, :create}
  before_action :require_the_president, :only => [:fire_the_missiles]
 
  private
 
  def set_user
    @user = somehow_find_and_set_the_user(params[:id])
  end
 
  def require_the_president
    @user.is_the_president?
  end
end 

The old *_filter callbacks still work and are not deprecated; so, you can still use them if you wish.

FastAPI: The Modern Python Web Framework

  Introduction to FastAPI: The Modern Python Web Framework The world of web frameworks has always been competitive — from Django and Flask ...