Skip to content

Instantly share code, notes, and snippets.

@mzemel
Created October 4, 2014 06:50
Show Gist options
  • Save mzemel/cd27e3c4950a0d3d8b84 to your computer and use it in GitHub Desktop.
Save mzemel/cd27e3c4950a0d3d8b84 to your computer and use it in GitHub Desktop.
Implementation of attr_accessor
module Fatter
def self.included(base)
base.class_eval do
def self.fattr_accessor(_symbol)
raise "NotASymbol" unless _symbol.is_a? Symbol
ivar_as_symbol = ("@" + _symbol.to_s).to_sym
define_method(_symbol.to_s) do
self.instance_variable_get(ivar_as_symbol)
end
define_method(_symbol.to_s + "=") do |arg|
self.instance_variable_set(ivar_as_symbol, arg)
end
end
end
end
end
class Dawg
include Fatter
fattr_accessor(:name)
end
irb(main):024:0> fido = Dawg.new
=> #<Dawg:0x007f8361efff38>
irb(main):025:0> fido.name =
irb(main):026:0* end
SyntaxError: (irb):26: syntax error, unexpected keyword_end
from /Users/mzemel/.rbenv/versions/2.1.2/bin/irb:11:in `<main>'
irb(main):027:0> fido.name = "Fido"
=> "Fido"
irb(main):028:0> fido.name
=> "Fido"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment