Skip to content

Instantly share code, notes, and snippets.

@makersacademy
Forked from leoallen85/class_methods..rb
Created February 28, 2013 17:29
Show Gist options
  • Save makersacademy/5058486 to your computer and use it in GitHub Desktop.
Save makersacademy/5058486 to your computer and use it in GitHub Desktop.
class HTML
def initialize(str)
@str = str
end
# instance method (note it makes use of an instance variable)
def render
puts "<div>#{@str}</div>"
end
# class method - no instance variables here
def self.render_div(str)
puts "<div>#{str}</div>"
end
# class method
def self.render_link(link, title)
puts "<a href=#{link}>#{title}</a>"
end
# alternative syntax, this does exactly the same as above
class << self
# class method
def render_div(str)
puts "<div>#{str}</div>"
end
# class method
def render_link(link, title)
puts "<a href=\"#{link}\">#{title}</a>"
end
end # note the end
end
html_render = HTML.new("first instance")
another_html_renderer = HTML.new("second instance")
# instance methods
html_render.render
another_html_renderer.render
# class methods
HTML.render_div("Class method")
HTML.render_link("google.com", 'Google')
# We see class methods used all over the place
# for example in ActiveRecord::Base, when we call
# ModelName.find or ModelName.all we are calling a class method
#
#
# class ActiveRecord::Base
# def self.find(id)
# # do stuff
# end
# def self.all
# # do stuff
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment