Tuesday, 31 March 2015

Headless gem for simulating user

Headless is used in automation testing to simulate the user.
gem Headless is having dependency on selenium web-driver.
the advantage of headless is that it does not opens a browser window.
selenium web-driver is used to start the browser and simulate user activities

firstly install headless gem by command:

gem install headless


Create a new ruby file and save this code in that file.

require 'rubygems'
require 'headless'
require 'selenium-webdriver'

headless = Headless.new
headless.start

driver = Selenium::WebDriver.for :firefox
driver.navigate.to 'http://blog.grepruby.com'
puts driver.title

headless.destroy


Then run this command form console:

$ ruby file_name_with_path


you will found the title printed on console:

Grep Ruby Practices

try it yourself by replacing the url in this file.

Ruby all? method, Wow nice


As the name indicates returns a boolean value either true or false.
Takes a block as a argument if block is not supplied takes the default block({ |item| item }) as argument.

The source of all? says that it stores the result of iteration in the static variable and then perform the AND operation from the result of next iteration.

Lets do some logical with all?

[123,456,789].all?
=>true

[123,456,789].all?{|b| b > 100 }
=>true


[123,456,nil].all?
=>false

[123,456,789].all?{|b| b > 200 }
=> false

it will return true when all the array elements satisfies the condition written in block evaluates to true.

Custom Logging


For custom logging ruby provides a class called Logger, for custom logging create a method in your model or module which creates the log file by using:

def custom_logger
  @@custom_logger ||= Logger.new("#{Rails.root}/log/custom_logging.log")
end


hold this instance as a static variable so that all the instances share it.

This code will create the custom_logging file, now use the it as you use the usual rails logger.

This logger provides the same levels as of the rails logger.

custom_logger.info "test log data"
custom_logger.warn "test warning"
custom_logger.debug "test debug"
custom_logger.error "test debug error"
custom_logger.unknown "test unknown error"
custom_logger.fatal "test fatal error"

Check you log file all these statements would be written in it.

Monday, 30 March 2015

ActiveRecord::Store


The ActiveRecord::Store was introduced in Rails 3.2
The ActiveRecord::Store gives us the ability to store a hash to our database cloumn as serialized data.
store allows to declare store accessors, which acts as any other attribute of model, we have to declare the database column used for the store as a text, which gives us enough room to store our data in database.

How to use it :

class Test < ActiveRecord::Base
  store :setting_store, accessors: [:cost]
end


temp= Test.new
=>#<Test id: nil, setting_store: {}, created_at: nil, updated_at: nil>

As we can see there is empty setting_store hash.

lets set some value into it.

temp.cost = 150
=>150

we have store value to our setting_store hash let's check it.

temp
=>#<Test id: nil, setting_store: {:cost=>150}, created_at: nil, updated_at: nil>

lets access by its accessors
temp.cost
=>150

Friday, 27 March 2015

Javascript: Convert json to html view



json = {"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

function syntaxHighlight(json) {
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

syntaxHighlight(json)

Output::

Thursday, 5 March 2015

group_by is cool in Ruby :)

I am getting this object and I have to display these records on category basis

data = [{"category":"xyz","label":"test xyz label1","link":"testlink"},
{"category":"xyz","label":"test xyzlabel2","link":"testlink"},
{"category":"abc","label":"test abc label1","link":"testlink"},
{"category":"abc","label":"test abc label2","link":"testlink"},
{"category":"def","label":"test def label1","link":"testlink"},
{"category":"def","label":"test def label2","link":"testlink"}]

Desired Output:

  category 1
    record 1
    record 2
  category 2
    record 1
    record 2

Previously I was Using the following code.
- category = ""
- data.each do |d|
  - if category != d[:category]
    - category = d[:category]
    %h2= d[:category]
    %ul
  %li= d[:label]

  
The code I mentioned Displayed the records in order displayed above But this will break incase if we get response as:
data = [{"category":"xyz","label":"test xyz label1","link":"testlink"},
{"category":"abc","label":"test abc label1","link":"testlink"},
{"category":"xyz","label":"test xyzlabel2","link":"testlink"},
{"category":"def","label":"test def label1","link":"testlink"},
{"category":"abc","label":"test abc label2","link":"testlink"},
{"category":"def","label":"test def label2","link":"testlink"}]

The above code will Display:
category 1
  record 1
category 2
  record 1
category 1
  record 2
category 3
  record 1

for solving this Problem I changed my approach and used group_by, it takes a block as an argument and returns a hash,
by using group_by the scenario we have discussed will be handelled easily.

- data.group_by{ |d| d[:category] }.each do |d|
  %h2= d.first
  %ul
  - d.last.each do | result |
    %li = result[:label]

  
this reduced my code and now it looks better.