Task

  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Task as PDF for free.

More details

  • Words: 5,951
  • Pages: 57
rake routes | grep link # to filter links Ruby creates an abstract syntax tree that it then executes Java is object oriented. However, unlike Ruby, it is not fully object oriented. Java is object oriented. However, unlike Ruby, it is not fully object oriented. Ruby uses dynamic typing. Being strongly influenced by Perl, Ruby excels at regular expressions. Ruby’s modules provide a method for mixing in (mixins) methods from multiple classes, giving Ruby the functional equivalent of multiple inheritance without the namespace clashing, which saves us from many potential problems. access control in Ruby is determined dynamically at run time. Protected methods are only accessed by objects that are defined by the class and subclasses in Ruby Ruby odds = [1, 3, 5, 7] # array Hash

antonyms = { 'clean' => 'dirty', 'black' => 'white', 'fall' =>'fly', 'evil'=> 'good' } print antonyms['black'] # => white antonyms.type # => Hash

Iterators In Ruby, an iterator is a method that yields control to a passed code block using yield or Proc#call. antonyms.each { |i| print i } arr.collect {| obj | block } ­> anArray

Ruby can iterate over arrays,

­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ Returns a new array by invoking block once for every element, passing each element as a parameter to block. The result of block is used as the given element in the new array

For one line code blocks, use braces ({…}): 5.times {|i| puts i}

For iterators that use multiple lines, use do…end: 5.times do |i| puts i

puts Math.sqrt(i) end

Local Variables versus Methods If a local variable exists with the same name as a method, the local variable will be used unless you put parentheses behind the method or use self.methodName. def colors(arg1="blue", arg2="red") "#{arg1}, #{arg2}" end colors = 6 print colors

The above outputs 6. If you were expecting to use the color method, you might have been surprised. Using parentheses, in this case, would yield the desired result: def colors(arg1="blue", arg2="red") "#{arg1}, #{arg2}" end colors = 6 print colors("purple", "chartreuse")

This outputs:

purple, chartreuse def stringReplace(searchString, replaceString, fileName) # read the file content aFile = File.open(fileName, "r") aString = aFile.read aFile.close # replace/substitute ... aString.gsub!(searchString, replaceString) # write string back to file File.open(fileName, "w") { |file| file << aString } End ############## # replacing  file contents line wise line.

def stringReplace(searchString, replaceString, fileName) # read file content aString = File.readlines(fileName).to_s # replace/substitute ... aString.gsub!(searchString, replaceString) # write string back to file File.open(fileName, "w") { |file| file << aString } End ruby stringreplace.rb blue red blue.txt

render :nothing => true ['hello', 'great', 'world'].to_param # => hello/great/world ['hello', 'great', 'world'].to_query('words') # => words%5B %5D=hello&words%5B%5D=great&words%5B%5D=world #to_param is used after the question mark in a URI, #to_query after. Hope it makes things clear. :)

rake db:migrate RAILS_ENV = production <%= f.select("member_type", options_for_member_type,:include_blank => "Select",:selected => @member.member_type.to_s) %> class File def File.open_and_process(*args) f = File.open(*args) yield f f.close() end end File.open_and_process("testfile", "r") do |file|

while line = puts line end end produces: This is line This is line This is line

file.gets

one two three

[1,3,5,7].inject(0) {|sum, element| sum+element} # 16 [1,3,5,7].inject(1) {|product, element| product*element} # 105 Inject works like this: the first time the associated block is called, sum is set to inject’s parameter and element is set to the first element in the collection. The second and subsequent times the block is called, sum is set to the value returned by the block on the previous call. The final value of inject is the value returned by the block the last time it was called. There’s one final wrinkle: if inject is called with no parameter, it uses the first element of the collection as the initial value and starts the iteration with the second value. This means that we could have written the previous examples as In Ruby, anything but the two special values false and nil are considered true for purposes of an if statement. So match results like 0 and 10 count as true. A << [45] Equivalent to a.push[45] hash['bret'] = 'texas' hash.has_key?('bret') hash.empty? hash.values value is the Array ['texas'].

hash.keys value is the Array ['bret'].

["hi", "there"].collect { | value | value.capitalize } The result is ["Hi", "There"].

a = [ 1, 3, 5, 7, 9 ] a[1..3] = [3, 5, 7] a[1...3]= [3, 5] a[3..3] = [7] a[3..1] = ! [5, 7, 9] puts "No cars have been produced yet." if Car.count.zero?

i1, i2 = 1, 1 # parallel assignment (i1 = 1 and i2 = 1) def fib_up_to(max) i1, i2 = 1, 1 while i1 <= max yield i1 i1, i2 = i2, i1+i2 end end

# parallel assignment (i1 = 1 and i2 = 1)

fib_up_to(1000) {|f| print f, " " } produces: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

a = [1, 2] b = 'cat' a.each {|b| c = b * a[1] } a ! [1, 2] b !2 defined?(c) ! nil { # { {

:name => {"name": :name => :name =>

"Konata "Konata "Konata "Konata

Izumi", Izumi", Izumi", Izumi",

'age' 1: 2, 'age' 'age'

=> 16, "age": => 16, => 16,

1 => 2 }.to_json 16} 1 => 2 }.to_json(:only => [:name, 'age']) 1 => 2 }.to_json(:except => 1)

ruby script/plugin install http://svn.techno-weenie.net/projects/plugins/restful_authentication ruby script/generate authenticated user sessions \

 --include-activations  --stateful

<select name="sales_agent[customer_id]" id="sales_agent_customer_id">

Fortunately, for models, Rails has a simple and convenient helper-method to help you do this quicker–collection_select. The API is: collection_select("object_name", "field_name", list_of_objects, "value_field", "display_field") collection_select("sales_agent", "customer_id", @customers, "id", "name")

One final note: When you use this–in your views–you’ll need to select the collection first in your controller. Most likely you’ll use something like @customers = Customer.find(:all, :conditions => "owner_id = 3") or something similar to fetch the collection you want to display. <%= error_messages_for (:modelname) %> rake clone_structure_to_test to duplicate development database into the test database(without the data) Unit tests are for Models and functional tests are for Controllers. Functional tests don’t need a web server or a network. Use the @request & @response variables to simulate a web server. The solution to this is including a security token in non-GET requests which you check on the server-side. In Rails 2 or higher, this is a one-liner in the application controller: protect_from_forgery :secret => "123456789012345678901234567890"

1. before [ :create, :update ], [ :set_filename, :set_filesize, :generate_thumbnail ] Which is equivalent to: 1. 2. 3. 4. 5. 6.

before :create, :set_filename before :create, :set_filesize before :create, :generate_thumbnail before :update, :set_filename before :update, :set_filesize before :update, :generate_thumbnail

link_to "Save changes", url(:post, 1), :method => :put

<%= link_to “Click me”, {:action => “action_name”, :id => product}, :confirm => “Are you sure?” %>

find (:all, :conditions => “date available <= now()” :order => “date_available desc” )

validates_presence_of :fieldname1,fieldname2 is the field there? validates_numericality_of :fieldname is it a valid number? validates_uniqueness_of :fieldname is there already this value in the database? validates_format_of :fieldname matches against regular expression

Misc <%= sprintf(“%0.2f”, product.price) %> :id => product is shorthand for :id => product.id methods ending in ! are destructive methods (like wiping out values, etc destroy! or empty!) a built-in helper method number_to_currency will format strings for money

ending with -%> will suppress the new line that follows

use method h() to escape html & characters (prevent sql attacks, etc) - Plugins generally extend Rails - Ruby is extended through Rubygems <%= select_tag ("profile[specialties][]", options_for_select(@specialties,[5,7]), {:multiple => true,:style => "height:100px",:selected => ["5"]}) =============================================================== find(

%>

:all, :conditions => ['field1 = ? and field2 = ?', value1, value2] :group = > 'position', :order => 'created_at ASC', :select => 'title,position', :include => :comments, :limit => 5 )

Starting new Application: rails -d mysql myapp because SQLite3 is new database [Default Rails: 2.0.2] Or rails appname ruby script/server –e production ruby script/server –e development [Webrick default mode : development] Creating rails application with different versions: gem list rails • this command will list gem installed on your machine • Installing particular gem : gem install rails --version 2.0.2 --include-dependencies --no-rdoc --no-ri • rails _x.x.x_ e.g rails _2.0.2_ kalyanrajiv • rails _2.2.2

Installation To install the plugin on Edge Rails or Rails 2.1 and greater: script/plugin install git://github.com/mbleigh/acts-as-taggable-on.git

Seed Fu is a new Rails plugin that provides a simplified syntax for creating and maintaining "seed data," the pre-loaded data necessary to run an application. layout nil Representational State Transfer [REST] CRUD (Create Read Update and Delete) Yielding appropriate responses in the proper format, be it HTML, JavaScript, XML or RSS. my_ip = (require 'open-uri' ; open("http://myip.dk") { |f| /([0-9]{1,3}\.){3}[0-9]{1,3}/.match(f.read)[0].to_a[0] }) puts("\n\n\nIP address of server machine"+my_ip) ipOFRemote = request.remote_addr puts("\n\n\n remote =>"+ipOFRemote)

# 127.0.0.1

Bang Methods in Ruby? [e.g str.upcase! ] Spaceship operator  [always return -1,0,1] class Bid include Comparable attr_accessor :contractor attr_accessor :quote #This is called the spaceship #operator – must always return -1, 1, #or 0 def <=>(other_bid) if self.quote < other_bid.quote -1 elsif self.quote > other_bid.quote 1 else 0 end

end end Once this function is defined, use it by using the usual less_than, larger_than or equal_to operators ab a == b %q{'Single quoted' example – no escape} %Q{“Double quoted” example – no escape}

3.times { puts "Hello!" }

never using #intern again. Use #to_sym instead class String def to_sym eval ":#{self}" end  end If you had to write one yourself, you'd want:  class String    alias to_sym intern  end 

# Search the model's text and varchar fields

# # # # # # # # # # # # # #

text = a set of words to search for :only => an array of fields in which to search for the text; default is 'all text or string columns' :except => an array of fields to exclude from the default searchable columns :case => :sensitive or :insensitive :include => an array of tables to include in the joins. Fields that have searchable text will automatically be included in the default set of :search_columns. :join_include => an array of tables to include in the joins, but only for joining. (Searchable fields will not automatically be included.) :conditions => a string of additional conditions (constraints) :offset => paging offset (integer) :limit => number of rows to return (integer)

# :order => sort order (order_by SQL snippet) Exceptions to layout usage When you don't want an application to apply to a certain action.. say AJAX or RSS/xml output.. 1

layout 'application', :except => :create_with_ajax

1. Task.find_by_all_complete(false) => table name is Task, complete is field name and false is value for that column. Alternate way is : Task.find(:all, conditions => [‘complete=?’, false]

2. Task.find(:all, conditions => [‘complete=?’, false],:order => ‘created_at DESC’) Alternate Method => Task.find_by_all_complete(false, ,:order => ‘created_at DESC’) 3.

Multiple Conditions Conditions => [‘project_id = ? and complete = ?’, 5,false] Find through association File project.rb Class project < ActiveRecord:Base Has_many : tasks End File projectController.rb Class ProjectsController < ApplicationController def show @project = Project.find(params[:id]) @tasks = Task.find(:all, :conditions => [‘project_id=? and complete=?’, @project.id, false]) Alternateway @tasks = @project.tasks.find(:all, :conditions => [‘complete=?’, false]) Alternateway @tasks = @project.tasks.find_all_by_complete(false) #finding the incomplete tasks for this project end end

004_move_find_into_model class TaskController < ApplicationController def index @tasks = Task.find_all_by_complete(false, :order => ‘created_at DESC’) end end Alternateway @tasks = Task.find_incomplete Task.rb class Task < ActiveRecord::Base belongs_to : project def self.find_incomplete find_all_by_complete(false, :order => ‘created_at DESC’) end end class ProjectController < ApplicationController def show @projects = Project.find(params[:id]) @tasks = @project.tasks.find_all_by_complete(false, :order => ‘created_at DESC’) #Alternateway @tasks = @project.tasks.find_incomplete end end

001_caching_with_instance_variable application.rb # Filters added to this controller will be run for all controller in the application # Likewise, all the methods added will be available for all controllers class ApplicationController < ActionController::Base def current_user User.find(session[:user_id]) end end prompt>ruby script/console User.find(1) #this command will fetch first record from database. @current_user ||= User.find(1) # this will fetch record only once. It doesn’t matter how many times page is refreshed So, it will be better to write this way: def current_user @current_user ||= User.find(session[:user_id]) end Example: 005_using_with_scope Learn how to use with_scope - a very powerful method which will allow your custom find methods to accept any find options. Just like magic! class Task < ActiveRecord::Base belongs_to : project

def self.find_incomplete(options= {}) with_scope:find => options do Task.find_all_by_complete(false, :order => ‘created_at DESC’) end end end TaskController.rb Class TaskController < ApplicationController Def Index @tasks = Task.find_incomplete :limit=>20 end end ProjectsController.rb class ProjectController < ApplicationController def show @projects = Project.find(params[:id]) @tasks = @project.tasks.find_incomplete :limit:20 end end Example: 006_symbol_to_proc It may have a goofy syntax, but the Symbol#to_proc feature Rails adds allows you to do simple blocks very quickly and easily. Project.rb class ProjectController < ApplicationController::Base has_many:tasks

def self.all_names find(:all).collect(&:name) end end prompt>ruby script/console artworks = Artwork.find(:all) artworks.collect{|p| p.artis} # will get all artist in an array Alternate method artworks.collect(&:name) artworks.collect(&:name).collect(&:downcase) #will get all elements in downcase artwork.all?(&:valid) Result=>true artworks.all?(&:any) Result=>true artworks.each(&:save!) Artwork(:first).name Artwork.sum(:columnName) # As sum_columnName Artwork.sum(:columnName, :condition => ‘complete=0’) # As sum_columnName Artwork.maximum(:columnName, :condition => ‘complete=0’) # As sum_columnName ~ly average, minimum

007_all_about_layouts

Example: 008_content_for If you want to change something in the layout on a per-template basis, content_for is your answer! This allows templates to specify view code that can be placed anywhere in a layout. Insoshi Open Source Social Networking Platform <%= stylesheet_link_tag "application" %>

Todo List

<%= yield %>
index.rhtml.erb # file inside app/views/project <% content_for :head do%> #content_for is a helper method <%= stylesheet_link_tag "projects" %> <% end %>

Projects

    <% for project in @projects%>
  • <%= @projects.name %>
  • <% end %<


Insoshi Open Source Social Networking Platform <%= stylesheet_link_tag "application" %> <%= yield:head %>

Todo List

<%= yield %>
Example: 009_filtering_sensitive_logs Are you accepting sensitive user data? Passwords, credit card numbers, etc. By default, Rails stores all submitted parameters in plain text in the logs. This episode will show you how to filter this sensitive input so it doesn't show up in the log file. application.rb # Filters added to this controller will be run for all controller in the application # Likewise, all the methods added will be available for all controllers class ApplicationController < ActionController::Base filter_parameter_logging “password” #This command will help not to send password in log file. def current_user User.find(session[:user_id]) end

end Example: 010_refactoring_user_name_p1 Learn how to clean up your code through refactoring. This episode will show you how to move code from the view into the model to remove duplication and simplify the view. Show.rhtml.erb

Users

<% for user in @users %>
  • ”> <%= user.first_name %> <%= “#{user.middle_initial}.” unless user.middle_initial.nil? %> <%= user.last_name %>
  • <% end %> app/views/profile/show.rhtml.erb

    Profile

    Name: <%= @user.first_name %> <%= “#{@user.middle_initial}.” unless @user.middle_initial.nil? %> <%= @user.last_name %> <%= link_to ‘Users List’ users_path %>

    Alternateway

    Profile

    Name: <%= @user.full_name %>

    <%= link_to ‘Users List’ users_path %> if user.rb is like below class User < ActiveRecord::Base def full_name name = first_name + “ “ name += “#{middle_initial}. ” Unless middle_initial.nil? name +=last_name name #writing name this way will return name and don’t need to call @user method inside the model end end Now Show.rhtml.erb

    Users

    <% for user in @users %>
  • ”> <%= user.full_name %> Alternate way

    <%= link_to user.full_name, user_path(user) %>
  • <% end %> Example: 011_refactoring_user_name_p1 Testing and refactoring go hand in hand. Refactoring is all about improving code without changing its behavior. Testing is all about making sure you don't change the behavior while you are improving the code. user_test.rb require File.dirname(__File__) + ‘/../test_helper’ class UserTest < Test::Unit::TestCase fixtures:users def test_full_name_without_middle_initial user = User.new(:first_name => ‘John’, :last_name => ‘Doe’) assert_equal ‘John Doe’, user.full_name end end prompt> gem install autotest To test this example user_test.rb require File.dirname(__File__) + ‘/../test_helper’ class UserTest < Test::Unit::TestCase fixtures:users def test_full_name_without_middle_initial user = User.new(:first_name => ‘John’, :last_name => ‘Doe’)

    assert_equal ‘John Doe’, user.full_name end def test_full_name_with_middle_initial user = User.new(:first_name => ‘John’, :middle_initial => ‘H’, :last_name => ‘Doe’) assert_equal ‘John H. Doe’, user.full_name end def test_full_name_with_blank_middle_initial user = User.new(:first_name => ‘John’, :middle_initial => ‘’, :last_name => ‘Doe’) assert_equal ‘John Doe’, user.full_name end end user.rb class User < ActiveRecord::Base def full_name [first_name, middle_initial,last_name].compact.join(‘ ’) end end

    #to eliminate double space if middle_initial is nil so compact

    class User < ActiveRecord::Base def full_name [first_name, middle_initial_with_period, last_name].compact.join(‘ ’) nil so compact end

    #to eliminate double space if middle_initial is

    def middle_initial_with_period “#{middle_initial}.” unless middle_initial.nil ? end def middle_initial_with_period “#{middle_initial}.” unless middle_initial.blank ? end end Example: 012_refactoring_user_name_p3 In the final part of this series you will see how to refactor your tests. Keeping tests clean is important because it will make testing easier to do in the future

    Example: 034_named_routes ActionController::Routing::Routes.draw do |map| # Install the default routes as the lowest priority. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end Recommended named routes Running http://localhost:3000/projects/ When we want to make home page this url for the site

    Map.connect ‘’, :controller => ‘projects’, :action =>’index’ #This is not named route Now http://localhost:3000 is mapped with http://localhost:3000/projects/ After adding the above map Map.connect ‘home’, :controller => ‘projects’, :action =>’index’ #This is named route This will generate url_paths. <%= home_path %> # render / <%= home_url %> # render http://localhost:3000/ map.task_archieve ‘tasks/:year/:month’, :controller => ‘tasks’, :action => ‘archieve’ #year,month are placeholders can be used as <%= task_archive_path(2007,5) %> # tasks/2007/5 Alternateway: <%= task_archive_path(:year => 2007, :month=>5) %> One more example Map.resource :projects #controller = projects generates routes and bunch of routes Example: 46-catch-all-route request.request.url will output all querystring after http://localhost:3000/

    # routes.rb map.connect '*path', :controller => 'redirect', :action => 'index' # redirect_controller.rb def index product = Product.find(:first, :conditions => ["name LIKE ?", "#{params[:path].first}%"]) redirect_to product_path(product)

    end

    Example: 013_dangers_of_model_in_session UserController.rb class UserController < ApplicationController def prepare session[:user] = User.find(:first) redirect_to :action => ‘show’ end

    # prepare action to set the session

    def show @user = session[:user] end def update @user = session[:user] @user.name = “foo” #these changes are temporarily and will not be stored in a database. redirect_to :action => ‘show’ end end show.rhtml <%= debug(@user) %> # for checking what is going inside the model This will output like ---ruby/object:user attributes: name : Ryan id: “1”

    <% link_to ‘Update’, :action => ‘update’ %> # after clicking on this update action, username will be changed to foo user.rb class User < ActiveRecord::Base validates_presence_of :name end def update @user = session[:user] @user.name = “” @user.validate? redirect_to :action => ‘show’ end UserController.rb class UserController < ApplicationController def prepare session[:user_id] = User.find(:first).id redirect_to :action => ‘show’ end

    # prepare action to set the session

    def show @user = User.find(session[:user_id]) end def update @user = User.find(session[:user_id]) @user.name = “foo” #these changes are temporarily and will not be stored in a database. redirect_to :action => ‘show’

    end end Above is the right way to do that Example: 014_performing_calculations_on_models prompt$ script/console Task.find(:first).priority #priority is col name Task.sum(:priority) Task.sum(:priority, :conditions => ‘completed=0’) Task.maximum(:priority) Project has many tasks p = Project.find(:first) p.tasks.sum(:priority) equivalent to Select sum(priority) as sum_priority from tasks where (tasks.project_id = 1) Example: 015_fun_with_find_conditions Tasks.count(:all,:conditions => [“complete = ? and priority =?”, false,3] Tasks.count(:all,:conditions => [“complete = ? and priority =?”, false,nil] ) # here nil = null of sql Select count(*) as count_all from tasks where (complete =0 and priority =NULL) so this is wrong Tasks.count(:all,:conditions => [“complete = ? and priority is ?”, false,nil] Tasks.count(:all,:conditions => [“complete = ? and priority IN (?)”, false, [1,3]]) Select count(*) as count_all from tasks where (complete =0 and priority IN (1,3) ) Tasks.count(:all,:conditions => [“complete = ? and priority IN (?)”, false, 0..3]) # passing ranges Select count(*) as count_all from tasks where (complete =0 and priority IN (0,1,2) )

    In rails 1.2 Tasks.count(:all,:conditions => {:complete => false, :priority => 1” })

    #passing hash to queries

    Benefit is that we can pass other kind of object like: Tasks.count(:all,:conditions => {:complete => false, :priority => nil” }) and it will properly determines what nil is in this case. Tasks.count(:all,:conditions => {:complete => false,:priority => [1,3]”) Tasks.count(:all,:conditions => {:complete => false,:priority => 1..3”) Select count(*) as count_all from tasks where (complete =0 and `priority` between 1 and 3 ) Task.find_all_by_priority(1..3).size Example: 016_virtual_attributes REGISTER First Name Last Name Password schema.rb # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and

    # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 1) do create_table "users", :force => true do |t| t.column "first_name", :password t.column "last_name", :string t.column "last_name", :string end end new.rhtml

    Register

    <% form_for :user :url => users_path do |f| %>

    First Name
    <%= f.text_field :first_name %>

    Last Name
    <%= f.text_field :last_name %>



    Password
    <%= f.password_field :password %>

    <%= submit_tag ‘Register’ %>

    <% end %> Using virtual field for the above form :

    Register

    <% form_for :user :url => users_path do |f| %>

    Full Name
    <%= f.text_field :full_name %>

    Password
    <%= f.password_field :password %>

    <%= submit_tag ‘Register’ %>

    <% end %> user.rb

    class User < ActiveRecord::Base def full_name [first_name, last_name].join(‘ ‘) end def full_name=(name) split = name.split(‘ ’,2) self.first_name = split.first self.last_name = split. last end end Example: 017_habtm_checkboxes category.rb class Category < ActiceRecord :: Base has_and_belongs_to_many :products end products.rb class Product < ActiceRecord :: Base has_and_belongs_to_many :categories end _form.rhtml <%= error_messages_for ‘product’>

    Name
    <%= text_field :product, :name %>

    Price
    <%= text_field :product, :price%>

    <% for category in Category.find(:all) %>

    <%= check_box_tag “product[category_ids][]”, category.id, @product.cateogries.include?(category) %> <%= category.name %>
    <% end %>

    product_controller.rb #-------------------def create @product = Product.new(params[:product]) if @product.save flash[:notice] = “Product was successfully added” redirect_to :action => ‘index’ else render :action => ‘new’ end

    end #-------------------def edit @product = Product.find(params[:id]) end #-------------------def update @product = Product.find(params[:id]) if @product.update_attributes(params[:product]) flash[:notice] = “Product was successfully updated” redirect_to :action => ‘show’, :id => @product else render :action => ‘edit’ end end #-------------------def destroy Product.find(params[:id]).destroy redirect_to :action => ‘index’ end Console One more table is there i.e categories_products p = Product.find(:first) p.category_ids = [2,3] # category_ids method is provided by has_and_belongs_to_many :categories #--------------------

    def update params[:product][:category_ids] ||= [] #set to an empty array if not set any checkbox, this returns nil @product = Product.find(params[:id]) if @product.update_attributes(params[:product]) flash[:notice] = “Product was successfully updated” redirect_to :action => ‘show’, :id => @product else render :action => ‘edit’ end end Example: 018_looping_through_flash <% unless flash[:notice].nil? %>
    <% = flash[:notice] %>
    <% end %> <% unless flash[:error].nil? %>
    <% = flash[:error] %>
    <% end %> Alternate way <% flash.each do |key, msg| %> <%= content_tag :div, msg, :id => key %> # content tag for creating the div tag <% end %> Example: 019_where_administration_goes EpisodeController.rb class EpisodesController < ApplicationController

    def index @episodes = Episodes.find(:all, :order => ‘position DESC’) end def prepare session[:user_id] = User.find(:first).id redirect_to :action => ‘show’ end

    # prepare action to set the session

    def show @user = User.find(session[:user_id]) end def update @user = User.find(session[:user_id]) @user.name = “foo” #these changes are temporarily and will not be stored in a database. redirect_to :action => ‘show’ end end console script/generate scaffold episode ‘admin/episodes’ # for admin section http://localhost:3000/admin/episodes/list index.rhtml
    <% for episodes in @episodes %>
    #<%= episode.position %>


    #<%= episode. published_at.strftime(‘%b %d’) %>
    <% if admin? %>
    <%= link_to “Edit”, edit_episode_path(episode) %> <%= link_to “Destroy”, episode_path(episode) , :confirm => “Are you sure?”, :method => :delete %>
    <% end %>

    <%= episode.name %>

    #<%= episode. description %>
    #<%= link_to “Download”, episode.file_url %>
    <% end %>
    <% if admin? %>
    <%= link_to “New Episode”, new_episode_path %>
    <% end %> application.rb class ApplicationController < ActionController::Base session :session_key => ‘_railcasts_session_id’ helper_method :admin? # this makes admin method as helper method done to make which method must be available to view as well protected def authorize

    unless admin? flash[:error] = “unauthorized access” redirect_to home_path false #so that no other action executed after that end end def admin? false end

    #setting it to true and false we can check restricted access

    end http://localhost:3000//episodes/new class EpisodesController < ApplicationController before_filter :authorize, except => index def index @episodes = Episodes.find(:all, :order => ‘position DESC’) end def new @episode = Episode.new end #-------------------def create @episode = Episode.new(params[:episode ]) if @ episode.save flash[:notice] = “Successfully created episode” redirect_to :episodes_path

    else render :action => ‘new’ end end #-------------------def edit @ episode = Episode.find(params[:id]) end #-------------------def update @episode = Episode.find(params[:id]) if @ episode.update_attributes(params[:episode]) flash[:notice] = “Successfully updated episode” redirect_to : episodes_path else render :action => ‘edit’ end end #-------------------def destroy Episode.find(params[:id]).destroy flash[:notice] = “Successfully destroyed episode” redirect_to episodes_path end end Example: 021_super_simple_authentication

    Ecellent plugin acts_as_authenticated Script/plugin source http://svn.techno-weenie.net/projects/plugins Script/plugin install acts_as_authenticated Script/generate authenticated user account Rake db:migrate http://localhost:3000/account/index def admin? false end

    #setting it to true and false we can check restricted access

    => def admin? current_user.name == “admin” alternate current_user.admin? end class SessionController < ApplicationController def create sessioin[:password] = params[:password] flash[:notice] = “Successfully logged in” rediret_to home_path end def destroy reset_session flash[:notice] = “Successfully logged out” rediret_to login_path

    end end new.rhtml

    <% form_tag sessions_path do %> Password: <%= text_field_tag :password%> <% end %>

    def admin? Session[:password] == ‘foobar’ end g = Greeter.new("Pat") Greeter.instance_methods => ["method", "send", "object_id", "singleton_methods", "__send__", "equal?", "taint", "frozen?", "instance_variable_get", "kind_of?", "to_a", "instance_eval", "type", "protected_methods", "extend", "eql?", "display", "instance_variable_set", "hash", "is_a?", "to_s", "class", "tainted?", "private_methods", "untaint", "say_hi", "id", "inspect", "==", "===", "clone", "public_methods", "respond_to?", "freeze", "say_bye", "__id__", "=~", "methods", "nil?", "dup", "instance_variables", "instance_of?"] Greeter.instance_methods(false) => ["say_bye", "say_hi"]

    g.respond_to?("name") => false g.respond_to?("say_hi") => true g.respond_to?("to_s") => true class Greeter attr_accessor :name end g = Greeter.new("Andy") g.respond_to?("name") => true g.respond_to?("name=") => true g.say_hi Hi Andy!

    g.name="Betty" Using attr_accessor defined two new methods for us, name to get the value, and name= to set it.

    Example: 034_named_routes ActionController::Routing::Routes.draw do |map| # Install the default routes as the lowest priority. map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end

    ri20min.rb

    class MegaGreeter attr_accessor :names # Create the object def initialize(names = "World") @names = names end # Say hi to everybody def say_hi if @names.nil? puts "..." elsif @names.respond_to?("each") # @names is a list of some kind, iterate! @names.each do |name| puts "Hello #{name}!" end else puts "Hello #{@names}!" end end # Say bye to everybody def say_bye if @names.nil? puts "..." elsif @names.respond_to?("join") # Join the list elements with commas puts "Goodbye #{@names.join(", ")}. Come back soon!" else puts "Goodbye #{@names}. Come back soon!" end end

    end if __FILE__ == $0 #__FILE__ is the magic variable that contains the name of the current file. $0 is the name of the file used to start the program. mg = MegaGreeter.new mg.say_hi mg.say_bye # Change name to be "Zeke" mg.names = "Zeke" mg.say_hi mg.say_bye # Change the name to an array of names mg.names = ["Albert", "Brenda", "Charles", "Dave", "Englebert"] mg.say_hi mg.say_bye # Change to nil mg.names = nil mg.say_hi mg.say_bye end Hello World! Goodbye World. Come back soon! Hello Zeke! Goodbye Zeke. Come back soon! Hello Albert! Hello Brenda! Hello Charles! Hello Dave! Hello Englebert!

    Goodbye Albert, Brenda, Charles, Dave, Englebert. back soon! ... ...

    people = Hash.new people[:nickname] = 'IndianGuru' people[:language] = 'Marathi' people[:lastname] = 'Talim' puts people[:lastname]

    A block is like an anonymous function or lambda. a = <<END_STR This is the string And a second line END_STR # << appending to a string a = 'hello ' a<<'world.I love this world...' puts a

    def self.up

    Come

    create_table :changesets_issues, :id => false do |t| t.column :changeset_id, :integer, :null => false t.column :issue_id, :integer, :null => false end add_index :changesets_issues, [:changeset_id, :issue_id], :unique => true, :name => :changesets_issues_ids end

    Ruby Idioms def my_method(my_var) if my_var return my_var.size else return nil end end p my_method([something]) # 1 p my_method(nil) # nil def my_method(my_var) return my_var && my_var.size #if left operand is true; it return value of right operand [otherwise value of left operand] end def my_method(my_var) return my_var ? my_var.size : 0 #output 1 and 0 for above case end

    def my_method(my_var) return my_var ? my_var.size : nil #output 1 and nil for above case end

    Ruby Idioms [part II] def my_method Fruits = [“apple”,”banana”] Fruits += [“apple”] unless fruits.include?(“apple”) p Fruits end p my_method # will print [“apple”,”banana”] def my_method Fruits = [“apple”,”banana”] Fruits += [“orange”] unless fruits.include?(“orange”) p Fruits end p my_method # will print [“apple”,”banana”,”orange”] def my_method Fruits = [“apple”,”banana”] Fruits |= [“orange”] p Fruits end p my_method # will print [“apple”,”banana”,”orange”]

    Ruby Idioms [part III] def my_method(my_var) if my_var return my_var else return no end end p my_method(“something”) # “something” p my_method(nil) # “no” def my_method(my_var) return my_var || no #if left operand is true it is returned else right operand is returned end def my_method(my_var) my_var = my_var || no return my_var end def my_method(my_var) my_var ||= no return my_var end def my_method(my_var)

    my_var = “no” unless myvar return my_var end

    Ruby Idioms [part VI] def my_method Fruits = [“apple”,”banana”] A = Fruits[0] B = Fruits[1] End def my_method Fruits = [“apple”,”banana”] a, b = *Fruits end def my_method *Fruits = “apple”,”banana” A = Fruits[0] B = Fruits[1] End def my_method Fruits = [“apple”,”banana”] a, b, c = *Fruits, ‘mango’ #wrong a, b, c = ‘mango’, *Fruits #right way end

    def my_method fruits = [“apple”,”banana”] fn = [“Peanuts”, “cashew”, fruits] p fn end def my_method fruits = [“apple”,”banana”] fn = [“Peanuts”, “cashew”, fruits] fruits[0] = “mango” #this will not change actual contents for fruits and nuts but It will create copy p fn end def my_method fruits = [“apple”,”banana”] fn = [“Peanuts”, “cashew”, *fruits] fruits[0] = “mango” #this is case of reference so it will change actual value p fn end def my_favourites(*fruits) fruits = end my_favourites (:mango, :orange, :banana) #[:mango, :orange, :banana] p my_favourites

    Ruby Idioms [part V]

    val = [1,2,3] a, b, c = val #parallel assignement pa#1 pb#2 pc#3 def test [10, “tintin”] end val, str = test p val # 10 p str # “tintin” “bugs funny bunny” =~ /bugs(.+) bunny/ # . means any character except ‘\n’ + 1 or more +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    observe_field - Passing Parameters Home Page | All Pages | Recently Revised | Feed

    Passing the default parameter <%= observe_field 'search', :frequency => 0.5, :update => 'target_id', :url =>

    { :controller => '', :action=> 'list' }, :with => "'search=' + escape(value)" %>

    Passing multiple parameters <select name="section" id="section"> <%= observe_field "search", :url => {:controller => "search", :action => "list"}, :with => "'section='+ escape($('section').value) + '&search=' + escape(value)", :update => "search_results" %>

    To answer an earlier question here: Each parameter passed in should be escaped. Otherwise, the right sequence of characters can create additional parameters. While probably not a security risk, it’s good practice and guarantees the users’ input will be passed in full.

    Another Way I couldn’t get the above example to work…perhaps due to the fact that I was using the Rails Form Helpers and not the HTML Form tags. A little research into the prototype.js documentation I found at Particletree helped me come up with the following: <%= observe_field("field1", :frequency => 1, :update => "span1", :url => {:action => :calculate_total}, :with => "'values='+escape(value) + ' ' + $F('field2')") %>

    I used the $F function from the prototype library to add the value of the additional field. In my controller, the ‘values’ string from the :with argument is passed into params[:values]. I can then use string manipulators (which is why I added the space between the two field values) to access the values I need to perform the server side operations and then render them in the partial(s) I choose. Like so:

    def calculate_total a = params[:values] i = a.split[0].to_i i2 = a.split[1].to_f i2 = i2/100 cv = i - (i*i2) render :text => cv.to_s end

    Hope this helps someone…

    Yet Another Way Here is another way to pass multiple parameters documented here. Using Prototype Form.serializeElements() function, you can achieve the same thing, and it has the advantages of preserving the params key assigned to the html elements if they are created using form_for or fields_for. observe_field :target_dom_id, :url => some_named_route_url, :method => :get, :with => "Form.serializeElements($('text_field_one', 'text_field_two', ...))"

    Default method Don’t forget that simply doing this: <%= observe_field("field1", :frequency => 1, :update => "span1", :url => {:action => :calculate_total}, :with => "stuff") %>

    will put the current value of ‘field1’ into params[:stuff] accessible to your RJS templates. But, be warned that if the field contains an ampersand (&), more than one params element may be passed. For example, if in field1 an end user typed in “hello&hi=greetings”, then params[:stuff]"hello" params[:hi]“greetings”

    This is usually not the desired behavior, so you’ll probably want to use :with => “‘stuff=’+escape(value)”

    which, in this example, will result in params[:stuff]==“hello&hi=greetings”

    Escaping ≠ no problems While i solved the &-problem using :with => "'value='+escape(value)"

    it still fails to submit ‘+’-signs. First i considered a client and server solution (replacing on client and back-replacing on server) but after reading that the escape-method is deprecated i tried the alternatives and this works well for me: :with => "'value='+encodeURIComponent(value)"

    Identical Format to a Form Submit If you’re using something like <%= password_field "user", "password", :size => 20, :value=>"" %>

    to create your form and would like to have a partial ajax submit through an observe_field call to have the same format as the final full form submit then use this format. ie. here combined password and password confirmation. <%= observe_field "user_password_confirmation", ... :with => "'user[password_confirmation]=' + encodeURIComponent(value) + '&user[password]=' + encodeURIComponent($('user_password').value)" %>

    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ require 'date' y2k = Time.gm(2000, 1, 1) y2k + 1 y2k - 1 y2k + (60 * 60 * 24 * 365)

    # # # #

    => => => =>

    Sat Sat Fri Sun

    y2k_dt = DateTime.new(2000, 1, 1) (y2k_dt + 1).to_s (y2k_dt - 1).to_s (y2k_dt + 0.5).to_s (y2k_dt + 365).to_s

    # # # #

    => => => =>

    "2000-01-02T00:00:00Z" "1999-12-31T00:00:00Z" "2000-01-01T12:00:00Z" "2000-12-31T00:00:00Z"

    Jan Jan Dec Dec

    01 01 31 31

    00:00:00 00:00:01 23:59:59 00:00:00

    UTC UTC UTC UTC

    2000 2000 1999 2000

    Subtracting one Time from another gives the interval between the dates, in seconds. Subtracting one Date from another gives the interval in days: day_one day_two day_two day_one

    = = -

    Time.gm(1999, 12, 31) Time.gm(2000, 1, 1) day_one day_two

    day_one = DateTime.new(1999, 12, 31)

    # => 86400.0 # => -86400.0

    day_two = DateTime.new(2000, 1, 1) day_two - day_one day_one - day_two

    # => Rational(1, 1) # => Rational(-1, 1)

    # Compare times from now and 10 seconds in the future. before_time = Time.now before_datetime = DateTime.now sleep(10) Time.now - before_time # => 10.003414 DateTime.now - before_datetime # => Rational(5001557, 43200000000)

    The activesupport gem, a prerequisite of Ruby on Rails, defines many useful functions on Numeric and Time for navigating through time:[2] [2]

    So does the Facets More library. require 'rubygems' require 'active_support' 10.days.ago 1.month.from_now 2.weeks.since(Time.local(2006, 1, 1))

    # => Wed Mar 08 19:54:17 EST 2006 # => Mon Apr 17 20:54:17 EDT 2006 # => Sun Jan 15 00:00:00 EST 2006

    y2k - 1.day y2k + 6.3.years 6.3.years.since y2k

    # => Fri Dec 31 00:00:00 UTC 1999 # => Thu Apr 20 01:48:00 UTC 2006 # => Thu Apr 20 01:48:00 UTC 2006

    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    Related Documents

    Task
    May 2020 54
    Task
    November 2019 50
    Task
    August 2019 99
    Task
    May 2020 38
    Task 4
    November 2019 27
    Task & Stdwork_trevor'scase
    October 2019 27