Wednesday 17 October 2012

Zip the files and download all in rails 3

In one of my project client asked me to give download all link for one folder which contains files. For that i have used this method which is using Tempfile to store files temperorily, zip files together using 'rubyzip' gem.

use this in your gem file,

gem 'rubyzip'

run bundle install

#controller

def download_all
      @records = Record.all
      if !@records.blank?
      file_name = 'download_files.zip'
      t = Tempfile.new("temp-filename-#{Time.now}")
      Zip::ZipOutputStream.open(t.path) do |z|
        @records.each do |img|
          file_path = img.image_name.to_s
          z.put_next_entry(file_path)
          z.print IO.read(img.image_name.path)
        end
      end
      send_file t.path, :type => 'application/zip', :x_sendfile=>true,
        :disposition => 'attachment',
        :filename => file_name
      t.close
    end
  end






Thank you guys..

Wednesday 9 May 2012

Ruby on Rails 3 Testing with Cucumber

Cucumber is used for Behaviour Driven Development.
Cucumber lets software development teams describe how software should behave in plain text. The text is written in a business-readable domain-specific language and serves as documentation, automated tests and development-aid - all rolled into one format.
Cucumber works with Ruby, Java, .NET, Flex or web applications written in any language. It has been translated to over 40 spoken languages.
Install cucumber for Rails 3:
Install Cucumber, Rspec-rails and capybara gem

sudo gem install cucumber-rails
sudo gem install database_cleaner
sudo gem install rspec-rails
sudo gem install capybara
  • Cucumber is a behavior driven development (BDD) framework in particular good for integration and functional tests
  • RSpec is a behavior driven development (BDD) framework for low level testing in the Ruby language
  • database_cleaner performs DB cleanup in testing
  • capybara simulating a browser, automating a browser or setting expectations using the matchers.



Using Cucumber to test rails 3 application:


  • Create a new Rails application store
$rails new store -d mysql
  • Edit the Gemfile
Include the Cucumber gems in a Rails 3 application
 group :test, :development do
    gem 'rspec-rails'
    gem 'cucumber-rails'
     gem 'capybara'
     gem 'database_cleaner'
 end
  • bundle install
  • Install the cucumber skeleton files to a Rails 3 application.
$ rails generate cucumber:install 



The cucumber-rails generator creates the directories:
features/step_definitions
features/support
The cucumber-rails generator creates the files:
config/cucumber.yml
features/support/env.rb
lib/tasks/cucumber.rake
script/cucumber
$rake cucumber



Create cucumber features:



  • Create a Cucumber Feature for Rails 3 application testing
$vi features/manage_store.feature
  • Cucumber Feature is the business user testing specification written in plain English with a specific format
Feature Format
 Feature: ...
   In order ...
    Some Actor ...
   Should ...
 
   Scenarior: ...
      Given ...
      And ...

     When ...
     AND ...
 
     Then ...
     AND ...
Implement the testing steps and Rails model code for Cucumber on Rails :
  • Create Cucumber step definitions
$vi features/step_definitions/order_steps.rb
  • Cucumber uses regular expression to match string and pass it to the step definitions
  • Run Cucumber
$rake cucumber



An example might be the ability to manage companies:
Feature: Manage companies

 In order to keep track of companies
 
 A user

  Should be able to manage companies


Scenario: Create a new company

 Given I am logged in

 When I create a new company named Acme

 Then I should see that a company named Acme exists



features/

companies.feature

steps/

company_steps.rb



Given == Setup

Given "I am logged in" do

user = Factory(:user)

visits new_session_path

fills_in ‘Login’,

:with => user.login

fills_in ‘Password’, :with => user.password

clicks_button ‘Login’

end



Given "I am logged in" do

user = Factory(:user)

visits new_session_path

fills_in 'Login',

:with => user.login

fills_in 'Password', :with => user.password

clicks_button 'Login'

end



When == Change

When "I create a new company named $name" do |name|

visits new_company_path

fills_in 'Name', :with => name

clicks_button 'Create'

end


Then == Outcome

Then "I should see that a company named $name exists" do |name|

response.body.should =~ Regexp.new(name)

end



At every step you need to run cucumber and check for the result.

Tuesday 10 April 2012

Using Regular Expression in Ruby on Rails — Regexp for Password Validation

A regular expression (abbreviated as regexp or regex, with plural forms regexps, regexes, or regexen) is a string that describes or matches a set of strings, according to certain syntax rules. Regular expressions are used by many text editors and utilities to search and manipulate bodies of text based on certain patterns. Many programming languages support regular expressions for string manipulation. Ruby has a strong Regular Expression engine built directly as a class of Ruby Programming language as Regexp
Here we will go through an example which will validate the password string.
Lets say we have to implement the following validations to validate a password…
  • Password should contain atleast one integer.
  • Password should contain atleast one alphabet(either in downcase or upcase).
  • Password can have special characters from 20 to 7E ascii values.
  • Password should be minimum of 8 and maximum of 40 cahracters long.
To fulfill above requirements we can have a regular expression like…


/^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/


in ruby programming language we can have a number of ways to define this regular expression as…
  • reg = Regexp.new(“^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$”)
or
  • reg = %r(^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$)
or simply
  • reg = /^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/

Now look what exactly this regex is doing…
(?=.*\d) shows that the string should contain atleast one integer.
(?=.*([a-z]|[A-Z])) shows that the string should contain atleast one alphabet either from downcase or upcase.
([\x20-\x7E]) shows that string can have special characters of ascii values 20 to 7E.
{8,40} shows that string should be minimum of 8 to maximum of 40 cahracters long.
We can simply use this regular expression for manual handling of password in an action as…

 

def validate_password(password)

  reg = /^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/

return (reg.match(password))? true : false

end
 

How to implement this regular expression in a model class in ruby on rails for password validation ?
To implement this regular expression in the model class in the rails way we can do it like…

class MyModel validates_format_of :password, :with => /^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,40}$/ end




Thank you...

Monday 9 April 2012

Rails 3.2.3 has been released!

This release changes the default value of config.active_record.whitelist_attributes to true. This change only affects newly generated applications so it should not cause any backwards compatibility issues for users who are upgrading but it may affect some tutorials and introductory material. For more information see the mass assignment section of the ruby on rails security guide
Rails 3.2.3 also introduces a new option that allows you to control the behavior of remote forms when it comes to authenticity_token generation. If you want to fragment cache your forms, authenticity token will also get cached, which isn't acceptable. However, if you only use such forms with ajax, you can disable token generation, because it will be fetched from meta tag. Starting with 3.2.3, you have an option to stop generating authenticity_token in remote forms (ie. :remote => true is passed as an option), by setting config.action_view.embed_authenticity_token_in_remote_forms = false. Please note that this will break sending those forms with javascript disabled. If you choose to not generate the token in remote forms by default, you can still explicitly pass :authenticity_token => true when generating the form to bypass this setting. The option defaults to true, which means that existing apps are NOT affected.
We've also adjusted the dependencies on rack-cache and mail to address the recent security vulnerabilities with those libraries. If you are running a vulnerable version of mail or rack-cache you should update both gems to a safe version. There were also some regressions in the render method that were fixed in this version.

CHANGES since 3.2.2

Action Mailer
  • Upgrade mail version to 2.4.3 
Action Pack
  • Fix #5632, render :inline set the proper rendered format.
  • Fix textarea rendering when using plugins like HAML. Such plugins encode the first newline character in the content. This issue was introduced in https://github.com/rails/rails/pull/5191
  • Do not include the authenticity token in forms where remote: true as ajax forms use the meta-tag value DHH
  • Turn off verbose mode of rack-cache, we still have X-Rack-Cache to check that info. Closes #5245.
  • Fix #5238, rendered_format is not set when template is not rendered. 
  • Upgrade rack-cache to 1.2.
    Fixes layout rendering regression from 3.2.2
    Active Model
  • No changes
Active Record
  • Added find_or_create_by_{attribute}! dynamic method.
  • Whitelist all attribute assignment by default. Change the default for newly generated applications to whitelist all attribute assignment. Also update the generated model classes so users are reminded of the importance of attr_accessible.
  • Update ActiveRecord::AttributeMethods#attribute_present? to return false for empty strings.
  • Fix associations when using per class databases. 
  • Revert setting NOT NULL constraints in add_timestamps fxn
  • Fix mysql to use proper text types. Fixes #3931. 
  • Fix #5069 - Protect foreign key from mass assignment through association builder.
Active Resource
  • No changes
Active Support
  • No changes
Railties
  • No changes

SHA-1

  • SHA-1 (actionmailer-3.2.3.gem) = 04cd2772dd2d402ffb9d9dbf70f5f2256c598ab3
  • SHA-1 (actionpack-3.2.3.gem) = 06d51ebd0863e0075d9a3e89a2e48dcc262c4e0c
  • SHA-1 (activemodel-3.2.3.gem) = 3f648213b88bb3695e2bce38ff823be99535f401
  • SHA-1 (activerecord-3.2.3.gem) = a9810e79d720994abbe24aded2bcb783bb1649b4
  • SHA-1 (activeresource-3.2.3.gem) = 3d1de8a80122efbcf6c8b8dfc13a7ab644bb2ca3
  • SHA-1 (activesupport-3.2.3.gem) = 6a63d75c798fb87d081cbee9323c46bec4727490
  • SHA-1 (rails-3.2.3.gem) = 4db7e5c288f5260dc299d55ec2aad9a330b611fc
  • SHA-1 (railties-3.2.3.gem) = 39a887de71350ece12c784d3764b7be2c6659b32

Wednesday 28 March 2012

Database dumping to your rails application

To take database backup

$ mysqldump -u root -p[password] [dbname] > [backupfile.sql]


To dump all MySQL databases on the system, use the --all-databases shortcut

 $ mysqldump -u root -p[password] --all-databases > [backupfile.sql]


To restore database

$ mysql -u root -p [password] [database_to_restore] < [backupfile]