Ruby Require v/s Load

Ruby Require v/s Load

When your code file grows. Then it is required to group them in multiple separate files.
Ruby require and the load is used to include ruby file into your code.

Ruby Require

  • The require method allows you to load a library and prevents it from being loaded more than once.
  • The require method will return ‘false’ if you try to load the same library after the first time.
  • The require method only needs to be used if the library you are loading is defined in a separate file, which is usually the case.
  • You also don’t need to specify the “.rb” extension of the library file name.

Here’s an example of how to use require. Place the require method at the very top of your “.rb” file:

require 'test_library'

Ruby Load

  • The load method is almost like the require method except it doesn’t keep track of whether or not that library has been loaded.
  • While using load, you must specify the “.rb” extension of the library file name.

Here’s an example of how to use load. Place the load method at the very top of your “.rb” file:

load 'test_library.rb'

Advertisements

Shell commands in Ruby

We can perform shell commands in Ruby via back ticks, exec and system. Note that each one returns something slightly different:

Back ticks( ` ): wget http://www.yahoo.com

Exec: exec(‘wget http://www.yahoo.com’)

System: system(‘wget http://www.yahoo.com’)

Ruby Open classes

Ruby’s Object#send allows access to private methods

In Ruby, classes are never closed: you can always add methods to an existing class. This applies to the classes you write as well as the standard, built-in classes. All you have to do is open up a class definition for an existing class, and the new contents you specify will be added to whatever’s there.

Ruby allows external access to private methods via the Object#send method.

Here is a small example:
class MyClass
    private
      def say_hello(name)
        puts “Hello, #{name}.”
      end
end
my_object = MyClass.new
We get smacked if we try:
> my_object.say_hello
Nomethoderror: private method `say_hello’ called for #<MyClass:0x820b4>
from (irb):8
from :0

but instead:
> my_object.send :say_hello, “world”
Hello, world.

Ruby on Rails guidelines for styling

Here are the few styling principles which i gathered from different site. Hope it helps.
1. Use two spaces per indentation level. No hard tabs.
  def some_method
    do_something
  end
  if a
    “hi”
  else
    “bye”
  end
2. Use spaces around operators, after commas, colons and semicolons, around { and before }
  ex:
    a, b = 1, 2
    1 > 2 ? true : false; puts ‘Hi’
    a = 10 + 20
3. No spaces after (, [ or before ], ).
    a = [1,2,3]  # array
4. Use a break when your stating a new method, and also dont use break after comment and method
    #here goes the methods
    def hi
      # something
    end
    def bye
      #something
    end
5. Align the parameters of a method call if they span more than one line.
    # if we have some method like this:
    def send_mail(source)
      Mailer.deliver(to: ‘bob@example.com’, from: ‘us@example.com’, subject: ‘Important message’, body: source.text)
    end
    # it can be clearly organizized as follows
    def send_mail(source)
      Mailer.deliver(to: ‘bob@example.com’,
                     from: ‘us@example.com’,
                     subject: ‘Important message’,
                     body: source.text)
    end
6. Dont use parenthesis if they dont have any arguments.
    def hi()
      #something
    end
    #use as follows
    def hi
      #something
    end
7.  if/unless
  #Never use then for multi-line if/unless.
    if some_condition then
      # something
    end
  # use this….
    if some_condition
      # do_something
    end
  #even good options like
    do_something if some_condition
  # another good option
    some_condition and do_something
  #Favor unless over if for negative conditions and Never use unless with else.
    do_something unless some_condition
  # another option
    some_condition or do_something
8. we can use ternary operator over if/then/else/end , and if we have nested if else dont prefer ternary operators. ie., ternary operator must not be nested
  result = some_condition ? something : something_else
  nested ex:
    if some_condition
      nested_condition ? nested_something : nested_something_else
    else
      something_else
    end
9.Don’t use parentheses around the condition of an if/unless/while like if (x > 10), unless the condition contains an assignment
  # use
    if x > 10
      # do something
    end
10.Prefer {…} over do…end for single-line blocks. Avoid the same for multiline blocks
  # good
  names.each { |name| puts name }
  # bad
  names.each do |name|
    puts name
  end
11. Use spaces around the = operator when assigning
12. Don’t use the return value of = (an assignment) in conditional expressions.
13. Use ||= freely to initialize variables.  Don’t use for boolean variables
    # set name to Rails, only if it’s nil or false
    name ||= ‘Rails’
14. Use snake_case for symbols, methods and variables. Use CamelCase for classes and modules
    :saySomething
    def someMethod
      …
    end
    # or
    def some_method
      …
    end
    class SomeClass
    end
15. comment the code where ever it is required.
    Use TODO to note missing features or functionality that should be added at a later date.
    Use FIXME to note broken code that needs to be fixed.
    Use OPTIMIZE to note slow or inefficient code that may cause performance problems.
    Use HACK to note code smells where questionable coding practices were used and should be refactored away.
    Use REVIEW to note anything that should be looked at to confirm it is working as intended.
16. class hierarchy
  # extend and include go first
  # constants are next
  # afterwards we have attribute macros
  # followed by other macros (if any) like validates
  # public class methods are next in line
  # followed by public instance methods
  # protected and private methods are grouped near the end
  protected
  private
17. Collections
  arr = []
hash = {}
STATES = %w(draft open closed)  # array using %w instead of []
even we can use SET which avoid duplicate, which deals good enough with unique elements
  Prefer symbols instead of strings as hash keys.
  ex:
    hash = { one: 1, two: 2, three: 3 }
  Prefer string interpolation instead of string concatenation:
  ex:
    email_with_name = “#{user.name} <#{user.email}>”
  Quick mass assignments
    a, b, c, d = 1, 2, 3, 4
  Union
  array union: just a pipe operator makes that:
    [1, 2, 1, 2, 3] | [1, 2, 3, 4] #=> [1, 2, 3, 4]
  Difference
    [1, 2, 3] – [3, 4, 5] #=> [1, 2]
    Now, that may not have been exactly what you were expecting. Difference works by taking the elements on the left and comparing them to the elements on the right. Whatever is different in the left is what’s returned. So the opposite of the above example looks like this:
    [3, 4, 5] – [1, 2, 3] #=> [4, 5]
  Intersection
    It removes duplicates. To perform an intersection you use the ampersand method as an operator.
    [1, 1, 3, 5] & [1, 2, 3] #=> [ 1, 3 ]
  Join
    [1, 2, 3] * 3 == [1, 2, 3, 1, 2, 3, 1, 2, 3]
    ex:
      h = { :name => “Fred”, :age => 77 }
      h.map { |i| i * “=” } * “and”              # => “age=77 and name=Fred”

Months – number to month names

Here is a method which converts numbers to month names:

Here is an sample console code, where i worked on

irb(main):030:0> months = Hash.new
=> {}
irb(main):031:0> (1..12).each {|m| months[m] = Date::ABBR_MONTHNAMES[m]}
=> 1..12
irb(main):032:0> months
=> {1=>”Jan”, 2=>”Feb”, 3=>”Mar”, 4=>”Apr”, 5=>”May”, 6=>”Jun”, 7=>”Jul”, 8=>”Aug”, 9=>”Sep”, 10=>”Oct”, 11=>”Nov”, 12=>”Dec”}

virtual attribute

If i dont want to store instances in the model, and if we need the attribute in views then we can go for Virtual attributes.

then add the attribute as foolows in model: ex: gender in employee table

attr_accessible :address, :age, :name, :gender

attr_accessor :gender

then you can use as same as in the views.

if we need the value: @employee.gender (same)

RedCloth

RedCloth is a Ruby library for converting Textile into HTML.

Textile is a simple formatting style for text documents, loosely based on some HTML conventions.

use this inyour gem file:

gem ‘RedCloth’, :require => ‘redcloth’

$ Bundle update some_text= “Hi, this is _jyothi_”

raw RedCloth.new(some_text).to_html

o/p: “Hi, this is jyothi

Here are some formats:

h3.     Header 3.
bq.     Blockquote.
#       Numeric list.
*       Bulleted list.
_emphasis_
__italicized__*strong*
**bold**
??citation??
-deleted text-
+inserted text+
^superscript^
~subscript~
@code@
%(classname)span%

==notextile== (leave text alone)

"This is a link (This is a title)":http://www.textism.com

table:
|a|simple|table|row| 
|And|Another|table|row|

style:
table{border:1px solid black}.

{background:#ddd;color:red}. |a|red|row|

for full referece: https://github.com/jgarber/redcloth

Entity-Relationship Diagram (ERD) for your Rails App models

Rails ERD is a Rails gem that allows you to easily generate a ER diagram based on your Active Record models. The diagram gives an overview of how your models are related. Having a diagram that describes your models is perfect documentation for your application.

Steps to follow:

1) Install Graphviz (Rails ERD requires Graphviz.)

sudo aptitude install graphviz (Ubuntu)

2) Add ‘rails-erd’ gem to your existing app’s Gemfile:

gem “rails-erd”

3) To install bundle:

bundle install

4)check the installed gem

bundle show rails-erd

5) Open your rails console and type:

bundle exec rake erd filetype=pdf

or   bundle exec rake erd filetype=dot

Other options:

rake erd orientation=vertical title='My model diagram'

other useful details about rail-erd gem : http://rails-erd.rubyforge.org/customise.html

Now go to your application root directory, you will get there erd.pdf or erd.dot file.

Issues in creating the erd digram:

try to install nodejs and rubyrace gem as well

$ sudo apt-get install nodejs

$ gem install therubyracer

If still any error install ruby racer use the below command.

$ gem install libv8 — –with-system-v8

Difference b/w .nil?, .empty? and .blank?

.nil? can be used on any object and is true if the object is nil.

.empty? can be used on strings, arrays and hashes and returns true if:

  • String length == 0
  • Array length == 0
  • Hash length == 0

Because empty? is not defined for all objects you would get a NoMethodError if you called empty? on nil so to avoid having to write things like if x.nil? || x.empty? Rails adds the blank? method.

That is where .blank? comes in. It is implemented by Rails and will operate on any object as well as work like .empty? on strings, arrays and hashes.

Difference between Modulus and division operator in ruby

Lets have an example:
If  a= 10, b= 20

 / Division – Divides left hand operand by right hand operand b / a will give 2
% Modulus – Divides left hand operand by right hand operand and returns remainder b % a will give 0

In simple:

division operator is used for finding “quotient” &
modular operator is used for finding “remainder” of a particular operation
for ex:-
if we divide 15 by 3 we get
quotient = 5 & remainder = 0
i.e 15 / 3 = 5(quotient)
& 15%3 = 0(remainder)

similarly if we divide 12 by 10 we get
quotient = 1 & remainder = 2
i.e 12 / 10 = 1(quotient)
12%10 = 2(remainder)