Skip to content

Instantly share code, notes, and snippets.

@vinniefranco
Last active August 29, 2015 14:21
Show Gist options
  • Save vinniefranco/703b3c6637cf31d28b1f to your computer and use it in GitHub Desktop.
Save vinniefranco/703b3c6637cf31d28b1f to your computer and use it in GitHub Desktop.
# When Ruby initializes a program, it instantiates all objects.
#
# This fires your class definitions as if they were methods.
# To illustrate here's an example
class Neat
p 'I am called' # straight to stdout!
# You can dynamically define class constants!
%w(ONE TWO THREE).each_with_index { |const, index| const_set const, index+1 }
end
# IT WORKS!!!
p "Neat::ONE == #{Neat::ONE}" #=> Neat::One == 1
# There are no primitives. It's objects all the way down... then it's turtles.
p true.class #=> TrueClass (Boolean in Opal)
p (false.is_a? Object) ? "OBJECT!" : "Must be PHP?" #=> "OBJECT!"
# Often times when I am transitioning developers from other languages, things
# can feel like magic.
#
# Things like attr_reader, attr_writer, has_many :things
# etc. etc.
class Bar
attr_accessor :wut # WUT WIZARDRY IS THIS?!?!?
end
bar = Bar.new
bar.wut = 'WUT!'
p bar.wut #=> 'WUT!'
# It becomes quite a bit easier if you explain that it's just a method call.
# Let's implement our own attr_reader, attr_writer, attr_accessor to explain...
class Foo
def self.my_attr_accessor(*instance_syms)
my_attr_reader(*instance_syms)
my_attr_writer(*instance_syms)
end
def self.my_attr_writer(*instance_syms)
instance_syms.each do |instance_sym|
define_method(:"#{instance_sym}=") do |value|
instance_variable_set :"@#{instance_sym}", value
end
end
end
def self.my_attr_reader(*instance_syms)
instance_syms.each do |instance_sym|
define_method(instance_sym) { instance_variable_get :"@#{instance_sym}" }
end
end
my_attr_accessor :bar, :baz
end
foo = Foo.new
foo.bar = 'WHOA!'
foo.baz = 'BEHOLD!'
p "foo#bar => #{foo.bar}" #=> foo#bar => WHOA!
p "foo#baz => #{foo.baz}" #=> foo#baz => BEHOLD!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment