codedecoder

breaking into the unknown…


Leave a comment

jQuery datpicker with date of Birth validation

We often have date element in our forms, like for entering date of birth, joining date, delivery date etc. We provide, the user with a calender to enter the date. A number of plugin available out there for entering date to form input. But, We will use datepicker plugin of jQuery here. We will then validate the date enter by the user on the form submit. Note, that a date selected from datepicker is always a valid date fromat, but user can change it manually in the text box if he want and enter some wrong date… testing person always do it :)

Lets below is our simple form with one input field with id = dob and a submit button.

<form>
   <label>Your Date of Birth</label>
   <input type="text" value="" id="dob" />
   <input type="submit" value="Submit" id="form-submit" />
</form>

We will going to validate date for its correct format (assuming dd-mon-yyyy format) and other things like, it should not be less than the current date.

jQuery(function(){
  //attach the datepicker to input with id dob after page load
  $(document).ready(function(){
  //yearRange will determine no of years to show in year select box. currently it will list 100 year 
  from now .  setting changeMonth and changeYear to true will show month and year box in calender, 
  otherwise user will able to select day only.The format given here means date should be like 
  13-May-2013. all possible format is available here

  $("#dob").datepicker({
          yearRange: "-100:+0",
          changeMonth: true,
          changeYear: true,
          dateFormat : "d-M-yy"
       });

    })

  // defining the function doing the date validation .our date format should be like 13-May-2013
  var validated_dob = function(dob){
             var dob_split = dob.split("-") #split the dob string into array
             var validated = "Yes"
             var msg = "Date of Birth is valid"
             var month_array = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]

             // make sure that day year and month entered or return
             if(dob_split.length != 3){
                            validated = "NO"
                            msg = "Date of Birth must be entered in this format: DD-MON-YYYY"
                            return [validated, msg]
                }

             // make sure that day month and year in DD-MON-YYYY format
            if ((dob_split[2].length != 4) || (dob_split[1].length != 3) || 
                                 !(dob_split[0].length == 2 || dob_split[0].length == 1)){
                            validated = "NO"
                            msg = "Date of Birth must be entered in this format: DD-MON-YYYY"
                            return [validated, msg]
                        }

             // make sure that day month have only integer
             if((!(/^[0-9]+$/).test(dob_split[0])) || (!(/^[0-9]+$/).test(dob_split[2]))){
                           validated = "NO"
                           msg = "Date of Birth day and year can have only numeric value"
                           return [validated, msg]
              }

             // make sure that day is in range 1-31
             if(dob_split[0] > 31 || dob_split[0] <= 0){
                            validated = "NO"
                            msg = "Date of Birth day should have value in 1-31"
                            return [validated, msg]
               }

            // make sure that month entered as Jan Feb etc
            if($.inArray(dob_split[1],month_array ) < 0){
                           validated = "NO"
                           msg = "Date of Birth month should be in ['Jan', 'Feb', 'Mar', 'Apr', 'May', 
                                                    'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]"
                           return [validated, msg]
             }

           // these variable are defined here instead of top because datepicker
           // can parse only a valid date, so if date is wrong it will throw error
           var user_dob =$.datepicker.parseDate("d-M-yy", dob)
           var today_date = new Date()
           if(user_dob > today_date){
                           validated = "NO"
                           msg = "Your Date of Birth can't be less than Today's Date"
                           return [validated, msg]
            }

           // if all condition pass, return original value at top
           return [validated, msg]
        }

       // validate the date on form submit
    $("#form-submit").click(function(e){
              // collect value return by validated_dob in a variable
              var check_dob = validated_dob(dob)
              // if validation return No, alert the error message and return
              //false i,e prevent the form from submit
              if (check_dob[0] == "NO"){
                            alert(check_dob[1])
                            return false
               }
     })
})

Referance:

http://api.jquery.com/Types/ # will tell you all type of data in jquery

http://api.jquery.com/Types/#Array # detail on jQuery array
http://api.jquery.com/jQuery.inArray/ # matching a element in array, will return -1 if no element matched or index of element if matched
http://api.jquery.com/category/miscellaneous/dom-element-methods/ # list method for traversing dom
http://api.jqueryui.com/datepicker/ # detail documentation of datepicker


Leave a comment

prevent right click on page : jquery contextmenu

contextmenu, tell a user of available options with a data element like links , input etc. You have observed a list of options shown to you when you right click on a webpage like : “reload”, “view page source” etc, similarly when you right click a link, it show you options like : “open in new window”, “open in new tab”  etc. These are the examples of contextmenu implemented by browser i,e they are default features of each browser. You can create your own context menu when needed in your application. Say you application is for managing image gallery, then you want, the right click to provide “copy”, “cut”, “save”, “downlaod” etc options on right click of a folder or image. A no of plugin are available there, to write custom contextmenu . some of them are listed below

http://medialize.github.io/jQuery-contextMenu/

http://plugins.jquery.com/contextMenu/

for people working on Rubu on Rails, gems also available for developing contextmenu

https://github.com/medialize/jQuery-contextMenu

https://github.com/joewalnes/jquery-simple-context-menu

Well, I have not tried any of the above plugin or gems, as my current requirement was not to set contextmenu, but to prevent it. I’ am working on financial domain website, and for security reason they do not want the user to access any contextmenu provided by the browser. So basically they want to disable right click on the page . It can be, achieved by the few lines of code. just put the below lines of code on page , you want to prevent the right click.

<script type=”text/javascript”>
  $(document).ready(function(){
    $(document).bind(“contextmenu”,function(e){
      alert(“For Security Reason Right Click Disabled on This Page”)
      e.preventDefault();
    });
  });
</script>

Note that contextmenu is a event like click, mouseover , keydown etc. So, to prevent it we have just prevented its default behaviour. complete list of events is available here at the bottom of the page . contextmenu event is explained in detail here .


Leave a comment

custom rake task in rails

rake command is explained in this post. rails provide a number of inbuilt tasks, but you can create your own task also as explained here.

=> Understanding the basics :

When you create any new rails project(example: rails new my_finance), you will find a file called Rakefile in your project root directory. It has below content in it

#!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.

require File.expand_path('../config/application', __FILE__)

MyFinance::Application.load_tasks # load_tasks method will make all your task available to rake

You can see that, it has self explanatory message at top. So to create, any custom task, we will create a file with .rake extension in lib/tasks folder of our application.

=> Examples of rake tasks.

I will create here different rake task, demonstrating how to write a simple rake task, rake task with arguments and rake task with dependency. let us create a demoexamples.rake file in lib/tasks folder. We will add our custom tasks to this file. Below is the code examples.

namespace :demotask do

  desc "display the current environment of rake"
  task :current_environment do
    puts "You are running rake task in #{Rails.env} environment"
  end

  desc "You are going to meet a person"
  task :meet_a_person do
    puts "I meet a person on the way to my house"
  end

  desc "I will say hello to the person"
  task :say_hello => :meet_a_person do # It means meet_a_person is dependency of say_hello task
    puts "I said HELLO to the person"
  end

  desc "I will say hello to the person after meeting and check environment"
  task :hello_env => [:current_environment, :meet_a_person] do # multiple dependency can be 
                                                               #passed as array
    puts "I said HELLO to the person"
  end

  desc "going to call two of my friend"
  task :call_friend, [:friend1, :friend2] do |t, args| # task with two arguments
    args.with_defaults(:friend1 => "John", :friend2 => "Dough")
    puts t # print t to see what it contain
    puts args # print args to see what it contain and in which format
    puts "Hello #{args.friend1}"
    puts "Hello  #{args.friend2}"
  end

  desc "see what happen when you call a modal method without loading environment"
  task :without_environment do
    puts User.first.full_name
  end

  desc "load environment before operating on any model object"
  task :with_environment => :environment do
    puts User.first.full_name
  end

  desc "count number of records in given model table"
  task :count_records, [:model] => :environment do |t, args| # task with both arguments and dependency
    args.with_defaults(:model => "User" )
    model_calss_name = Object.const_get(args.model) # this is very important as when you#pass argument it come as a string, so you must convert it to model class
    puts "No of records is #{model_calss_name.count}"
  end

end

The point to note above is the use of below concept:

namespace : It will group your task in a namespace, thus avoiding any conflict if task with same name already exists. You can skip it if you want, but use it as good convention

desc : It describe the function your task is going to perform. You can skip it if you want, but use it as good convention

task: it contain the code which perform your desire action. I have just printed simple messages but you can do anything in the do end block

name of the task : task is followed by name of the task as symbol like :meet_a_person,  :say_hello etc

arguments : arguments are passed as array, following the name

dependency : the dependent task to be performed before performing a task is passed as array after =>

=> Listing the custom task

As usual, now when you run rake -vT. It will list the task name with description of what you can do with that task

$ rake -vT

rake demotask:call_friend[friend1,friend2]              # going to call two of my friend
rake demotask:count_records[model]                      # count number of records in given model table
rake demotask:current_environment                       # display the current environment of rake
rake demotask:hello_env                                 # I will say hello to the person after meeting and check environment
rake demotask:meet_a_person                             # You are going to meet a person
rake demotask:say_hello                                 # I will say hello to the person
rake demotask:with_environment                          # load environment before operating on any model object
rake demotask:without_environment                       # see what happen when you call a modal method without loading

=> Running the rake task from terminal

I will show you how to run these task from terminal, with small description where ever needed.

$ rake demotask:current_environment # below is the output , as no environment is passed default development is taken
You are running rake task in development environment

$ rake demotask:current_environment RAILS_ENV=staging # here see how we are passing the environment in which task need to be run
You are running rake task in staging environment

$ rake demotask:current_environment RAILS_ENV=production # this time passing production environment
You are running rake task in production environment

$ rake demotask:meet_a_person # this will just print the message
I meet a person on the way to my house

$ rake demotask:say_hello # see that since meet_a_person is dependency of say_hello, its code is executed first
I meet a person on the way to my house # this message coming from  meet_a_person task, executed first as being a dependency
I said HELLO to the person # hello is printed now, if dependency fail, this task will also fail

$ rake demotask:hello_env #this task have multiple dependency, each called in order they are specified in the task
You are running rake task in development environment
I meet a person on the way to my house
I said HELLO to the person

$ rake demotask:call_friend # you have not passed any argument so default will be printed, also see the value stored in t and args variable
demotask:call_friend # coming from t variable, thus it contain the task name
{:friend1=>”John”, :friend2=>”Dough”} # see that args is generated as a hash
Hello John
Hello  Dough

passing arguments to rake command in rails 3 . when you define any task with argument, while passing it from console, do not use space between different argument otherwise will throw error as below.
$ rake demotask:call_friend["arun", "sanjay"]
rake aborted!
Don’t know how to build task ‘demotask:call_friend[arun,' # see that task name is choped when space encountered , so do not use space between argument
/home/arun/.rvm/gems/ruby-1.9.3-p194@threepiller/gems/rake-10.0.4/lib/rake/task_manager.rb:49:in `[]‘
/home/arun/.rvm/gems/ruby-1.9.3-p194@threepiller/gems/rake-10.0.4/lib/rake/application.rb:142:in `invoke_task’
/home/arun/.rvm/gems/ruby-1.9.3-p194@threepiller/gems/rake-10.0.4/lib/rake/application.rb:70:in `run’
(See full trace by running task with –trace)

$ rake demotask:call_friend["arun","sanjay"] # passing argument to rake task
demotask:call_friend
{:friend1=>”arun”, :friend2=>”sanjay”}
Hello arun
Hello  sanjay

$ rake demotask:without_environment # task fail as environment is not loaded so, model, gems, library function etc is not available to rake
rake aborted!
uninitialized constant User

$ rake demotask:with_environment # this will work as this task load environment as its dependency
Jeff Smith

NOTE : for a rake task to use all the methods in your gems, you library, your models i,e available anywhere in your application, you must load environment as its dependency. see with_environment task written above

$ rake demotask:count_records # will count the number of records from User model table
No of records is 13 #my user table have 13 records

$ rake demotask:count_records[Role] # will count the number of records from Role model table, passed here as argument
No of records is 7 #my role table have 7 records


Leave a comment

bootstrap popover

Bootstrap provide a number of js plugin listed here. Here I will create a popover to display message about the input to be filled,when a user try to enter something in it. Let us first define a input field on which we implement popover.

In ruby on rails it has below syntax.

<%=text_field_tag "routing_number", @loan[:RoutingNumber] , 
'data-content'=>"Routing Number is a 9 digit number starting with 0, 1, 2 or 3.",
'data-placement'=>"top"
%>

The important point above to note is the use of data attribute to add any value to a html element in unobtrusive way. Any property provided by bootstrap can be added in this way (i,e ‘data-property’ => ‘value’). I have set the property content and placement in the above code. the value set to data-content will give the text to be shown in the popover and data-placement will decide whether it appears right left top or bottom.Other available property for popover listed here is animation , html, selector, trigger, title, delay and container .

The above code in pure html can be written as below

<input type="text"  name="routing_number" id="routing_number" 
data-content="Routing Number is a 9 digit number starting with 0, 1, 2 or 3." data-original-title=""
data-placement="top"
/>

Now we will write our jQuery code to add popover on the input. When a user type a character, popover will appear with the message. It will be removed when he click anywhere out side i,e if input get blur

var showpopup = function(){
$(this).popover('show')
};

var hidepopup = function(){
$(this).popover('hide');
};

$("#routing_number").keypress(showpopup); # will show the popover on enter of a charecter
$("#routing_number").blur(hidepopup); # will hide the popover

The other event available for popover besides show and hide is destroy and toggle . Also note the use of jQuery events keypress and blur . other event listed here is change(), focusin(), select(), submit() .


1 Comment

rake db:seed in rails

rake command is explained in this post . writing custom rake task is explained in this post.  db:seed is inbuilt rake task defined by rails. The rake db:seed command, basically execute whatever code you write in db/seeds.rb file of your application. Though can write any code in this file, by convention you should write code which populate your database with the basic data, for example: when ever your deploy your application somewhere, and create a new database for it, you want that user with admin credential must be present there. So you will write the code which create that user in this file. Below is the sample code which will create a user and assign admin role to him.

puts "********Seeding Data Start************"

admin = User.create(:first_name => 'System', :last_name => 'Admin', 
       :email => 'systemadmin@sunpower.com', :password => 'sunpoweradmin', 
       :password_confirmation => 'sunpoweradmin', :source_system_id => 'systemadmin', 
       :source_system => 'LP',:entity_type => "Customer", :target_system => "OPENAM")

if admin.errors.blank?
    puts "***User #{admin.first_name} #{admin.last_name} created ***"
    admin.add_role :admin # add_role is method defined by rolify gem
    puts "***admin role assigned to #{admin.first_name} #{admin.last_name}***"
else
    puts "admin user failed to create due to below reasons:"
    admin.errors.each do |x, y|
       puts"#{x} #{y}" # x will be the field name and y will be the error on it
     end
end

puts "********Seeding Data End************"

Now whenever you recreate your database, you just need to run below command to populate the database, with the basic data

$ rake db:seed RAILS_ENV=production

The correct order to setup database in production, with all the rake task available within db namespace is as below

$rake db:create RAILS_ENV=production

$rake db:migrate RAILS_ENV=production

$ rake db:seed RAILS_ENV=production

NOTE: You can replace the first two commands with $rake db:setup RAILS_ENV=production , it will run both create and migrate internally

=> COMPLETE LIST of rake db command in rails :

db:create creates the database for the current env
    db:create:all creates the databases for all envs
db:drop drops the database for the current env
db:drop:all drops the databases for all envs
db:migrate runs migrations for the current env that have not run yet
db:migrate:up runs one specific migration
db:migrate:down rolls back one specific migration
db:migrate:status shows current migration status
db:migrate:rollback rolls back the last migration
db:forward advances the current schema version to the next one
db:seed (only) runs the db/seed.rb file
db:schema:load loads the schema into the current env’s database

db:schema:dump dumps the current env’s schema (and seems to create the db as well)

db:setup runs db:schema:load, db:seed
db:reset runs db:drop db:setup
db:migrate:redo runs (db:migrate:down db:migrate:up) or (db:migrate:rollback db:migrate:migrate) depending on the specified migration
db:migrate:reset runs db:drop db:create db:migrate


Leave a comment

what is rake in rails

rake is command line utility of rails. All commands available for rails are listed here . writing custom rake task is explained in this post . Below is the definition given for it in rails doc.

“Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility ‘make’, and uses a ‘Rakefile’ and .rake files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.”

Putting in simple word : “rake will execute different tasks(basically a set of ruby code) specified in any file with .rake extension from comandline.” .

rake is a gem in itself and installation dependency of rails i,e whenever you install a rails rake gem get installed along with it.

rails provide a number of inbuilt task like : db:create, db:migrate etc, you have been familiar with. You can define your own task (see here) also. list of all the task can be seen with below command.

$ rake -T #below is the list of task with small description of what they do. when you install a gem say cucumber or rcov or any othet, if they have defined any rake task it will get listed here.basically below is the list of all task available to you : the built one, those provided by installed gems or custome task wriiten by you
rake about                                              # List versions of all Rails frameworks and the environment
rake assets:clean                                       # Remove compiled assets
rake assets:precompile                                  # Compile all the assets named in config.assets.precompile
rake cucumber                                           # Alias for cucumber:ok
rake cucumber:all                                       # Run all features
rake cucumber:ok                                        # Run features that should pass
rake cucumber:rerun                                     # Record failing features and run only them if any exist
rake cucumber:wip                                       # Run features that are being worked on
rake db:create                                          # Create the database from DATABASE_URL or config/database.yml
rake db:drop                                            # Drops the database using DATABASE_URL or the current Rails.env
rake db:fixtures:load                                   # Load fixtures into the current environment’s database.
rake db:migrate                                         # Migrate the database (options: VERSION=x, VERBOSE=false).
rake db:migrate:status                                  # Display status of migrations
rake db:rollback                                        # Rolls the schema back to the previous version (specify steps w/ STEP=n).
rake db:schema:dump                                     # Create a db/schema.rb file that can be portably used against any DB
rake db:schema:load                                     # Load a schema.rb file into the database
rake db:seed                                            # Load the seed data from db/seeds.rb
rake db:setup                                           # Create the database, load the schema, and initialize with the seed data
rake db:structure:dump                                  # Dump the database structure to db/structure.sql.
rake db:version                                         # Retrieves the current schema version number
rake doc:app                                            # Generate docs for the app — also available doc:rails
rake jquery_ui_themes:import:google_cdn[version,theme]  # Import themes from Google CDN
rake jquery_ui_themes:import:themeroller[path,name]     # Import jQuery themeroller theme
rake loanpath:on_db_refresh                             # Actions to do after the db refresh
rake log:clear                                          # Truncates all *.log files in log/ to zero bytes
rake middleware                                         # Prints out your Rack middleware stack
rake notes                                              # Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)
rake notes:custom                                       # Enumerate a custom annotation, specify with ANNOTATION=CUSTOM
rake paperclip:clean                                    # Cleans out invalid attachments.
rake paperclip:refresh                                  # Refreshes both metadata and thumbnails.
rake paperclip:refresh:metadata                         # Regenerates content_type/size metadata for a given CLASS
rake paperclip:refresh:missing_styles                   # Regenerates missing thumbnail styles for all classes using Paperclip.
rake paperclip:refresh:thumbnails                       # Regenerates thumbnails for a given CLASS
rake rails:template                                     # Applies the template supplied by LOCATION=(/path/to/template) or URL
rake rails:update                                       # Update configs and some other initially generated files
rake rails_admin:disable_initializer                    # Disable rails_admin initializer / Disable rails_admin initializer
rake rails_admin:install                                # Install rails_admin / Install rails_admin
rake rails_admin:prepare_ci_env                         # CI env for Travis / CI env for Travis
rake rails_admin:uninstall                              # Uninstall rails_admin / Uninstall rails_admin
rake routes                                             # Print out all defined routes in match order, with names.
rake secret                                             # Generate a cryptographically secure secret key
rake spec                                               # Run all specs in spec directory (excluding plugin specs)
rake spec:controllers                                   # Run the code examples in spec/controllers
rake spec:helpers                                       # Run the code examples in spec/helpers
rake spec:lib                                           # Run the code examples in spec/lib
rake spec:mailers                                       # Run the code examples in spec/mailers
rake spec:models                                        # Run the code examples in spec/models
rake spec:rcov                                          # Run all specs with rcov
rake spec:requests                                      # Run the code examples in spec/requests
rake spec:routing                                       # Run the code examples in spec/routing
rake spec:views                                         # Run the code examples in spec/views
rake stats                                              # Report code statistics (KLOCs, etc) from the application
rake time:zones:all                                     # Displays all time zones, also available: time:zones:us
rake tmp:clear                                          # Clear session, cache, and socket files from tmp/
rake tmp:create                                         # Creates tmp directories for sessions, cache, sockets, and pids

In the above command we have passed -T option which list all the tasks for us. list of other available option for rake can be listed with –help option as below

$ rake –help
rake [-f rakefile] {options} targets…

Options are …
–backtrace=[OUT]            Enable full backtrace.  OUT can be stderr (default) or stdout.
–comments                   Show commented tasks only
–job-stats [LEVEL]          Display job statistics. LEVEL=history displays a complete job list
–rules                      Trace the rules resolution.
–suppress-backtrace PATTERN Suppress backtrace lines matching regexp PATTERN. Ignored if –trace is on.
-A, –all                        Show all tasks, even uncommented ones
-D, –describe [PATTERN]         Describe the tasks (matching optional PATTERN), then exit.
-e, –execute CODE               Execute some Ruby code and exit.
-E, –execute-continue CODE      Execute some Ruby code, then continue with normal task processing.
-f, –rakefile [FILE]            Use FILE as the rakefile.
-G, –no-system, –nosystem      Use standard project Rakefile search paths, ignore system wide rakefiles.
-g, –system                     Using system wide (global) rakefiles (usually ‘~/.rake/*.rake’).
-I, –libdir LIBDIR              Include LIBDIR in the search path for required modules.
-j, –jobs [NUMBER]              Specifies the maximum number of tasks to execute in parallel. (default:2)
-m, –multitask                  Treat all tasks as multitasks.
-n, –dry-run                    Do a dry run without executing actions.
-N, –no-search, –nosearch      Do not search parent directories for the Rakefile.
-P, –prereqs                    Display the tasks and dependencies, then exit.
-p, –execute-print CODE         Execute some Ruby code, print the result, then exit.
-q, –quiet                      Do not log messages to standard output.
-r, –require MODULE             Require MODULE before executing rakefile.
-R, –rakelibdir RAKELIBDIR,     Auto-import any .rake files in RAKELIBDIR. (default is ‘rakelib’)
–rakelib
-s, –silent                     Like –quiet, but also suppresses the ‘in directory’ announcement.
-t, –trace=[OUT]                Turn on invoke/execute tracing, enable full backtrace. OUT can be stderr (default) or stdout.
-T, –tasks [PATTERN]            Display the tasks (matching optional PATTERN) with descriptions, then exit.
-v, –verbose                    Log message to standard output.
-V, –version                    Display the program version.
-W, –where [PATTERN]            Describe the tasks (matching optional PATTERN), then exit.
-X, –no-deprecation-warnings    Disable the deprecation warnings.
-h, -H, –help                   Display this help message.


2 Comments

passing parameter with post method in REST

While making API call, you should avoid passing sensitive information like username, password, social security number etc in the url as anyone can easily read them. The safer way is to make call as post method and pass needed parameter in body. I find this security hole in one of my own code but rectified it before anyone can misuse it.

Below, is the code, which generate authentication token from Openam, which support SSO for my application. Authentication token is needed to perform all task like user creation, deletion etc on Openam. So any person who can get hold of my username and password can getback the authorization token also and hack in Openam

require 'rest_client'
 module Openam
 class Client

   attr_writer :base_url, :username, :password

   def initialize(base_url, username, password)
      @base_url = base_url
      @username = username
      @password = password
   end

   def generate_authorization_token
     uri = "#{@base_url}/authenticate?username=#{@username}&password=#{@password}"
     admin_authorization_token = RestClient.post(uri, 
                                          :content_type => "application/xml")
     admin_authorization_token.slice!(9..-1).strip
   end
  end
end

I have modified, the above generate_authorization_token method to use post method and pass parameter in body instead of url

def generate_authorization_token
   uri = "#{@base_url}/authenticate" # url to which request is made
   payload = {:username=>@username,:password=>@password} # hash containing 
                                                       username and password
   admin_authorization_token = RestClient.post(uri, payload, 
                            :content_type => "x-www-form-url-encoded")
   admin_authorization_token.slice!(9..-1).strip # this step will remove unwanted 
                                           charecter from the token
end

The main point here is the use of  “x-www-form-url-encoded” as content type which tell REST that url parameter is present in the Body and passing username and password parameter as hash in the payload

Follow

Get every new post delivered to your Inbox.