Category Archives: Ruby on Rails

Create your own Gem!-Part1

Hi All! today we are going to learn  how to create a gem from scratch!

STEP1: Choose a name for your gem and create an empty repository for the gem in GitHub.

Your Gem name must be unique so run a quick search in Github or Rubygems.org to check if the name has already been taken or use the following command:

$ gem list -r your_gem_name

*** REMOTE GEMS ***

If the gem name exists it would be returned as an output after you type the above command.

In this example, I have chosen my gem name to be ‘word_play’. You can find this in GitHub

STEP2: Inside your rails console, create the following folders and files for the gem you wish to create and follow the naming conventions, the below images shows  the required files/folders to be created for the gem ‘word_play’ :

General Layout of a Gemfile

General Layout of a Gemfile

Gemfile folders expanded

Gemfile folders expanded

Do not create the folders ‘doc’ and ‘word_play-0.0.1.gem’ file yet as I will explain more more about it later !

STEP3: The ‘lib’ folder and its contents

The source code of the gem would go into a ruby file which has the same name as the gem itself and is found under the ‘lib’ folder by convention.

word_play.rb

word_play_ruby_code

There is a another folder under the ‘lib’ folder, also with the same name as the gem and has a ruby file named ‘version.rb’ under it. It contains the version number of the gem embedded into it by the following ruby code:

module Mygem

VERSION = “0.0.1”

end

Every time we make any change in the gem, we should increment the gem’s version number before pushing it into rubygems.org or GitHub. The version  number of gem is of the form A.B.C , where A, B, C are non-negative integers. Remember the following rules while giving a version to the gem.

  • Increment in A.B.C for a backward incompatible changes to your public API, which is a major change.
  • Increment in A.B.C if new backward compatible functionality is introduced to the public API or if any public API functionality is deprecated, a minor change.
  • Increment in A.B.C for backward compatible bug fixes, a patch level change.

STEP4 The Gemspec file

The gemspec file consists of information about the gem. It contains details about the gem author, summary of its function, dependent gems, gem file path etc. It would be worthwhile to click the below image and learn more from the comments.

Gemspec file

Gemspec file

STEP5 Build and Install your gem

$ gem build word_play.gemspec

WARNING: no homepage specified
Successfully built RubyGem
Name: word_play
Version: 0.0.1
File: word_play-0.0.1.gem

$ gem install word_play-0.0.1.gem

Successfully installed word_play-0.0.1
1 gem installed

STEP6 Testing your gem

Testing your gem is very important. Your test cases should be under the ‘test’ folder or ‘spec’ folder as in my case. I have used rspec gem to test my code although one can use any gem for testing.

STEP7 Push your gem into GitHub or Rubygems.org

To push your gem into Rubygems.org, create an account in the website and in your rails console use the below command:

$ gem push word_play-0.0.1.gem

Enter your RubyGems.org credentials.
Don’t have an account yet? Create one at http://rubygems.org/sign_up
Email: sadicarnot@gmail.com
Password:
Pushing gem to https://rubygems.org…
Signed in.
Pushing gem to https://rubygems.org…
Successfully registered gem: word_play (0.0.1)

Use the following commands to push your gem into GitHub:

touch README.md  #(It is good to have a Readme file to explain how to use your gem)

git init

git add README.md

git commit -m “first commit”

git remote add origin git@github.com:Anu4ruby/your_gem.git

git push -u origin master

STEP 8: To Use your Gem, go to the ruby terminal and type the following commands.

$irb

require “word_play”
=> true

Word.is_anagram?(“scream”,”creams”)
The 2 words are anagram of each other
=> true

Word.is_palindrome?(“Madam”)
The word is a palindrome
=> true

STEP9 Delete your gem if you want!

first install the gemcutter gem and then use ‘gem yank’ command as below to remove your gem from rubygems.org:

$ gem install gemcutter

$ gem yank your_gem -v x.y.z (# you gem version number in x.y.z )

to remove your gem from GitHub, simply delete the gem repository.

That’s all for now. We now know how to create a basic gem and publish it. There are more features that can be added to a gem namely executable files, extensions and requiring more files into your gemfile. We will see about each of these in Part 2 of this blog.

Credits and References: I thank Stephen Ball and Ruby Gem Guides
who inspired me to write this blog.

Advertisements

Leave a comment

Filed under Ruby on Rails

Ruby-Difference between Public, Private and Protected methods!-Part1

Hello RoR developers! Welcome to my blog spot!

This blog is about Access Control in Ruby with relevant code snippets and is very useful for beginners. Advanced programmers may go through this topic to brush up their basics.

What is Access Control and Why do we need it ?

In order to protect data variables/methods from manipulation by external classes, it has to made accessible or visible to chosen classes. Ruby has 3 types of visibility to protect methods/variables:  Public, Private and Protected. We will look at each one them in detail now.

Public: When a method is declared a public, it means that objects of any class have direct access to it. For example in the below code snippet.

class Account

attr_reader :final_balance, :balance

RI = 0.5

def initialize(balance)

  @balance = balance

  @final_balance = @balance + interest

  final_balance = @final_balance

end

public

  def interest

  p ( @balance * self.class::RI )

  end

public

  def rewards(time)       

@reward_points = interest * time * final_balance * 0.1

p ‘Reward points = ‘,@reward_points

p ‘interest = ‘, interest

  end

 def compare (obj1,obj2)

 if (obj1.interest == obj2.interest)

p ‘true’

  else

p ‘false’

p obj1

p obj2

  end

end

end

class Savings < Account

RI = 0.9

end

class Checking < Account

RI = 0.2

end

class User

end

acc = Account.new(100)

sav = Savings.new(200)

chk = Checking.new(300)

usr = User.new

#Now call the instance method using the objects created and see the output

acc.interest # 50

sav.interest # 180

chk.interest # 60

usr.interest # undefined method for User

we observe that public methods are accessible by objects of the parents class ‘Account’ as well as the child class Savings and Checking.

Private & Protected: When a method is declared under private or protected visibility, it cannot be directly accessed by parent class or any of the sub classes. For example in the above code,suppose if we declare the function interest as private as below:

private  (# or protected)

def interest

p ( @balance * self.class::RI )

end

p acc.interest # no method error

p sav.interest # no method error

p chk.interest # no method error

p usr.interest # no method error

In order to access the private/protected methods of a class, Ruby allows implicit calls to private/protected methods through public methods. For example:

acc.rewards(10) # interest = 180

sav.rewards(5)  # interest = 19200

Checking.new(200).rewards(20) # interest = 40

The private/protected method ‘interest’ is accessed via the public method ‘rewards’ as per the definition below:

def rewards(time)

@reward_points = interest * time * final_balance * 0.1

p ‘Reward points = ‘,@reward_points

p ‘interest = ‘, interest

end

Now the most important question arises, what is the difference between private and protected. To understand this lets test both scenarios for the following code and observe the results:

private

def interest

p ( @balance * self.class::RI )

end

obj1 = Account.new(200)

obj2 = Savings.new(200)

Checking.new(200).compare(obj1,obj2) # Private method interest called for Account, NoMethod Error

Now declare the method interest as protected

protected

def interest

p ( @balance * self.class::RI )

end

obj1 = Account.new(200)

obj2 = Savings.new(200)

Checking.new(200).compare(obj1,obj2)

output:

# “false”

#Account:0x2733e70 @balance=200, @final_balance=300.0>

#Savings:0x2733e28 @balance=200, @final_balance=380.0>

 

This actually worked! but why! lets look at the function definition:

def compare (obj1,obj2)

if (obj1.interest == obj2.interest)

p ‘true’

else

p ‘false’

end

end

Inside the public method compare, obj1 of class Account and obj2 of class Savings makes an explicit/direct call to the method ‘interest’ (obj1.interest abd obj2.interest respectively) which is not permitted by Ruby for private methods. Whereas if the method is declared protected, objects of the parent class and its subclass objects can access the method when called inside a public method. Hence the visibility of private is lesser than a protected method.

I hope this blog was useful to some extent to understand different types of access control and their differences!

1 Comment

Filed under Ruby on Rails