About Me

My photo
जिंदगी की परीक्षा में कोई नम्बर नहीं मिलते है लोग आपको दिल से याद करे तो समझ लेना आप पास हो गए....

Saturday 30 April 2016

Useful sites

http://danknox.github.io/2013/01/27/using-rubys-native-nethttp-library/

Thursday 4 February 2016

Rails 4 way notes 1

1. Rails 4, generating a new application will result in the creation of binstubs for Rails executables, located
in the bin folder. A binstub is a script containing an executable that runs in the context of the bundle. This
means one does not have to prefix bundle exec each time a Rails specific executable is invoked. Binstubs are
also first class citizens in Rails 4, and should be added into your version control system like any other source
code file.
By default, the following stubs are available on every new Rails 4 project:
• bin/bundle
• bin/rails
• bin/rake

To add a binstub of a commonly used executable in your bundle, invoke bundle binstubs some-gem-name .
To illustrate, consider the following example:
$ bundle binstubs guard
which creates a binstub for guard in the bin folder.

2.Secret Token
Certain types of hacking involve modifying the contents of cookies without the server knowing about it.
By digitally signing all cookies sent to the browser, Rails can detect whether they were tampered with. The
secret_token.rb initializer contains the secret key base, randomly generated along with your app, which is
used to sign cookies.

p15
ref: rails 4 way

Ruby Learning Notes 1

.On Unix systems, you can use the “shebang” notation as the first line of the program file:#!/usr/bin/ruby
puts "Hello, Ruby Programmer"
puts "It is now #{Time.now}"

If you make this source file executable (using, for instance, chmod +x myprog.rb ), Unix lets you run the file as a program:

$ ./myprog.rb
Hello, Ruby Programmer
It is now 2013-05-27 12:30:36 -0500


If your system supports it, you can avoid hard-coding the path to Ruby in the “shebang” line by using
#!/usr/bin/env ruby , which will search your path for ruby and then execute it.




2.The ri tool is a local, command-line viewer for ruby documentation. Most Ruby distributions now also install the resources used by the ri program.
To find the documentation for a class, type ri ClassName. For example, the following is the summary information for the GC class. (To get a list of classes with ri documentation, type
ri with no arguments.)
$ ri GC

If you installed Ruby using rvm, there’s one additional step to get ri documentation available. At a
prompt, enter rvm docs generate .

3.Class A class is a combination of state and methods that use that state.

Naming Convention:
Local variables, method parameters, and method names should all start with a lowercase letter or an underscore. Global variables are prefixed with a dollar
sign ($), and instance variables begin with an “at” sign (@). Class variables start with two “at” signs (@@). Finally, class names, module names, and constants must start with an uppercase letter.

Hash: a hash by default returns nil when indexed by a key it doesn’t
contain.specifying a default value(which is by default nil) when you create a new, empty hash.
histogram = Hash.new(0)   # This overrides default value from nil to zero
histogram['ruby'] # => 0

Symbol: Symbols are simply constant names that you don’t have to  predeclare and that are guaranteed to be unique. A symbol literal starts with a colon and is
normally followed by some kind of name

Ruby statement modifiers are a useful shortcut if the body of an if or while statement is just a single expression.

if radiation > 3000
  puts "Danger, Will Robinson"
end

Here it is again, rewritten using a statement modifier:
puts "Danger, Will Robinson" if radiation > 3000


Regular expression: create a regular expression by writing a pattern between
slash characters (/pattern/)

We can put all this together to produce some useful regular expressions:
/\d\d:\d\d:\d\d/   # a time such as 12:34:56
/Perl.*Python/  #Perl, zero or more other chars, then Python
/Perl Python/    #Perl, a space, and Python
/Perl *Python/  #Perl, zero or more spaces, and Python
/Perl +Python/  #Perl, one or more spaces, and Python
/Perl\s+Python/  #Perl, whitespace characters, then Python
/Ruby (Perl|Python)/   #Ruby, a space, and either Perl or Python

The match operator =~ can be used to match a string against a regular expression. If the pattern is found in the string,=~ returns its starting position; otherwise, it returns nil . This means you can use regular expressions as the condition in if and while statements.

code blocks: which are chunks of code you can associate with method invocations, almost as if they were parameters.Code blocks are just chunks of code between braces or between do and end . This is a code block:
{ puts "Hello" }

a Ruby standard and use braces for single-line blocks and do / end for multiline blocks.

ARGV :When you run a Ruby program from the command line, you can pass in arguments. the array ARGV contains each of the arguments passed to the running program. Create a file called cmd_line.rb that contains the following:
puts "You gave #{ARGV.size} arguments"
p ARGV

When we run it with arguments, we can see that they get passed in:
$ ruby cmd_line.rb ant bee cat dog
You gave 4 arguments
["ant", "bee", "cat", "dog"]


The p method prints out an internal representation of an object.
b1 = BookInStock.new("isbn1", 3)
p b1

produces:
#<BookInStock:0x007fac4910f3e0 @isbn="isbn1", @price=3.0>

To read the instance variable of object out side the world we wrote attribute accessor method , but in ruby we need not to write for each instance variable since ruby provides shortcut for that "attr_reader", as example

class BookInStock

  attr_reader :isbn,:price
 def initialize(isbn,price)
   @isbn = isbn
   @price = price
 end
end

book = BookInStock.new("isbn1", 12.34)
puts "ISBN = #{book.isbn}"
puts "Price = #{book.price}"





~                             
Ruby provides a shortcut for creating these simple attribute-setting methods. If you want a write-only accessor, you can use the form attr_writer , but that’s fairly rare. You’re far more likely to want both a reader and a writer for a given attribute, so you’ll use the handy-dandy attr_accessor method:

pg36?(floating point)


References:

Programming Ruby: The Pragmatic Programmer's Guide

Tuesday 19 January 2016

Ruby On Rails Interview Questions and answers(2014-15)

Q1. Difference between include and extend in ruby?
Ans. There are two ways to add a given module in a class so we can use it's method in the class.

let's module is given below
module ReusableModule
  def module_method
    puts "Module Method: Hi there!"
  end
end
If we will add this module in a class using include then it's methods will become instance methods of that class.

class ClassThatIncludes
  include ReusableModule
end
ClassThatIncludes.new.module_method       # "Module Method: Hi there!"

If we will add this module in a class using extends then it's methods will become class methods of that class.

class ClassThatExtends
  extend ReusableModule
end

ClassThatExtends.module_method            # "Module Method: Hi there!"



Q2. What is Mixin?
Ans. 

  • A mixin can basically be thought of as a set of code that can be added to one or more classes to add additional capabilities without using inheritance. In Ruby, a mixin is code wrapped up in a module that a class can include or extend. In fact, a single class can have many mixins.

    Ruby does not support multiple inheritance directly but Ruby Modules have another wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.
    Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it.
    Let us examine the following sample code to gain an understand of mixin:
    module A
       def a1
       end
       def a2
       end
    end
    module B
       def b1
       end
       def b2
       end
    end
    
    class Sample
    include A
    include B
       def s1
       end
    end
    
    samp=Sample.new
    samp.a1
    samp.a2
    samp.b1
    samp.b2
    samp.s1
    Module A consists of the methods a1 and a2. Module B consists of the methods b1 and b2. The class Sample includes both modules A and B. The class Sample can access all four methods, namely, a1, a2, b1, and b2. Therefore, you can see that the class Sample inherits from both the modules. Thus, you can say the class Sample shows multiple inheritance or a mixin.

ref: http://www.tutorialspoint.com/ruby/ruby_modules.htm
       http://www.sitepoint.com/ruby-mixins-2/

Q3. What is difference between dynamic scaffolding and static scaffolding?
Ans.
Static Scaffolding:It create the code physically on disc. It creates a boilerplate code that we can modify later as per our requirement.it  generates all CRUD functionality with views and controllers
ruby script/generate scaffold Model Controller action1 action2

Dynamic scaffolding:  It create the code in memory only.It does the same as static scaffolding but at run time.No files are generated.Suited for simple functionality such an interface used only by admin for editing a list of option for users.It is done by adding a call to the scaffold method to a controller.

Class XyzController < ActionController::Base
   scaffold :xyz
end

With this configured, when you start your application the actions and views will be autogenerated at runtime. The following actions are dynamically implemented by default by the runtime scaffolding mechanism:
  • index
  • show
  • edit
  • delete
  • create
  • save
  • update
A CRUD interface will also be generated at runtime.






.

Q4. What do you mean by render or redirect to?
Ans. render causes rails to generate a response whose content is provided by rendering one of your templates. Means, it will directly goes to view page without executing action code.

redirect_to generates a response that, instead of delivering content to the browser, just tells it to request another url. Means it first checks actions in controller and then goes to view page.

Q5.What is Module?
Ans. Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits.
  • Modules provide a namespace and prevent name clashes.
  • Modules implement the mixin facility.

    Unlike classes, you cannot create objects based on modules nor can you subclass them.Modules stand alone; there is no "module hierarchy" of inheritance
Ref: http://rubylearning.com/satishtalim/modules_mixins.html
 




Q5. What is rjs?

Q6. Jquery callback? 

Q7. MyASM vs Innodb? 
Ans:
MYISAM:
  1. MYISAM supports Table-level Locking
  2. MyISAM designed for need of speed
  3. MyISAM does not support foreign keys hence we call MySQL with MYISAM is DBMS
  4. MyISAM stores its tables, data and indexes in diskspace using separate three different files. (tablename.FRM, tablename.MYD, tablename.MYI)
  5. MYISAM not supports transaction. You cannot commit and rollback with MYISAM. Once you issue a command it’s done.
  6. You can use MyISAM, if the table is more static with lots of select and less update and delete.
INNODB:
  1. InnoDB supports Row-level Locking
  2. InnoDB designed for maximum performance when processing high volume of data
  3. InnoDB support foreign keys hence we call MySQL with InnoDB is RDBMS
  4. InnoDB stores its tables and indexes in a tablespace
  5. InnoDB supports transaction. You can commit and rollback with InnoDB

Ref: http://stackoverflow.com/questions/12614541/whats-the-difference-between-myisam-and-innodb

Q8. 1st level normalization?
Ans.

Q9. Difference type of indexing on mysql?
Ans.

Q10. STI?
Ans.
1. STI is basically the idea of using a single table to reflect multiple models that inherit from a base model, which itself inherits from ActiveRecord::Base. 
2.In the database schema, sub-models are indicated by a single “type” column.
Steps: 
1. rails g model Team name:string position:string rank:integer type:string 
2. rails g model Hockey --parent Team 
3. rails g model Cricket --parent Team 

h = Hockey.create(name: 'Roop Singh',rank: 1,position: 'Captain') (0.3ms) begin transaction SQL (33.6ms) INSERT INTO "teams" ("type", "name", "rank", "position", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["type", "Hockey"], ["name", "Roop Singh"], ["rank", 1], ["position", "Captain"], ["created_at", "2015-10-11 05:35:31.592579"], ["updated_at", "2015-10-11 05:35:31.592579"]] (268.4ms) commit transaction => #<Hockey id: 1, name: "Roop Singh", position: "Captain", rank: 1, type: "Hockey", created_at: "2015-10-11 05:35:31", updated_at: "2015-10-11 05:35:31">  

Rails way
========
Active Record allows inheritance by storing the name of the class in a column that by default is named “type” (can be changed by overwriting Base.inheritance_column)

class Company < ActiveRecord::Base; end
class Firm < Company; end
class Client < Company; end
class PriorityClient < Client; end

When you do Firm.create(name: "37signals"), this record will be saved in the companies table with type = “Firm”. You can then fetch this row again using Company.where(name: '37signals').first and it will return a Firm object.

Be aware that because the type column is an attribute on the record every new subclass will instantly be marked as dirty and the type column will be included in the list of changed attributes on the record. This is different from non STI classes:
Company.new.changed? # => false
Firm.new.changed?    # => true
Firm.new.changes     # => {"type"=>["","Firm"]} 
 
 
Player => Footwall
       => Cricket

Address  = Shipping Address
                   Billing Address
User = Guest
            Admin
Q11. polymorphic relation?
Ans.
A slightly more advanced twist on associations is the polymorphic association. With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model. Here's how this could be declared:
class Picture < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
end
class Employee < ActiveRecord::Base
  has_many :pictures, as: :imageable
end
class Product < ActiveRecord::Base
  has_many :pictures, as: :imageable
end

Q12. Assets Pipeline?
Ans. 
The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages and pre-processors such as CoffeeScript, Sass and ERB.

Rails 4 automatically adds the sass-rails, coffee-rails and uglifier gems to your Gemfile, which are used by Sprockets for asset compression

1.The first feature of the pipeline is to concatenate assets, which can reduce the number of requests that a browser makes to render a web page. Web browsers are limited in the number of requests that they can make in parallel, so fewer requests can mean faster loading for your application.

In production, Rails inserts an MD5 fingerprint into each filename so that the file is cached by the web browser.

2.The second feature of the asset pipeline is asset minification or compression. For CSS files, this is done by removing whitespace and comments

3.The third feature of the asset pipeline is it allows coding assets via a higher-level language, with precompilation down to the actual assets. Supported languages include Sass for CSS, CoffeeScript for JavaScript, and ERB for both by default.

Q13. TDD vs BDD?
Ans.
  • Rspec is used for Unit Testing
  • Cucumber is used behaviour driven development. Cucumber can be used for System and Integration Tests.Cucumber for writing high-level acceptance tests.
Q14. Favourite gems?
Ans.
Paperclip : used for attachment upload.

exifr :EXIF Reader is a module to read metadata from JPEG and TIFF images.
EXIFR::JPEG.new('enkhuizen.jpg').gps.latitude       # => 52.7197888888889
EXIFR::JPEG.new('enkhuizen.jpg').gps.longitude      # => 5.28397777777778
 
Geocoder: Geocoder is a complete geocoding solution for Ruby. With Rails it adds geocoding (by street or IP address), reverse geocoding (finding street address based on given coordinates), and distance queries

Roo: Roo implements read access for all common spreadsheet types

Pry: best tool for debugging for runtime developer console.

PDFKit - to convert html to pdf.


Q15. ROR vs J2EE?
Ans.
 1.Rails requires less time and effort to get a website up and running.
 2. Rails requires much, much less code to accomplish the same task as it would require in J2EE.
Ex. x,y = 2
  java version:   var int x,y;
                          x = 1;
                          y = 2;

Q16 Ruby vs Java?
Ans.
1.Ruby code can be interpreted and does not need compilation. However, Java code needs to be compiled before interpretation.
2.java follows a strict C syntax in coding while Ruby allows the programmer to omit a few codes.(like semicolon)
3.Java code execution is faster than Ruby. The reason is that the Java  code is converted into machine language, and the Java Virtual machine  executes the code faster.


4. Ruby does not have type declarations, and you can assign a name to  variable as needed. In Java, every member variable belongs to some  class. Therefore, a programmer is required to declare the type of  variable and its name before using it in a code.
5. 
 



References:
http://api.rubyonrails.org/
http://stackoverflow.com/questions/156362/what-is-the-difference-between-include-and-extend-in-ruby
https://www.quora.com/Is-Java-J2EE-better-than-Ruby-on-Rails