Created
August 18, 2012 05:55
-
-
Save melborne/3384729 to your computer and use it in GitHub Desktop.
Inner DSL on Ruby sample?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
class User | |
@@users, @@id = [], 0 | |
attr_accessor :name, :age, :job | |
attr_reader :id | |
def initialize(name, age, job) | |
@@id += 1 | |
@id, @name, @age, @job = @@id, name, age, job | |
@@users << self | |
end | |
def to_s | |
"%d:%s(%d/%s)" % [id, name, age, job] | |
end | |
class << self | |
def register(cfg='userdata', &blk) | |
case | |
when blk then instance_eval(&blk) | |
when cfg then instance_eval ::File.read(cfg) | |
else raise ArgumentError | |
end | |
rescue Errno::ENOENT | |
abort "userdata file `#{cfg}` not found" | |
end | |
alias :add :new | |
def all | |
@@users | |
end | |
[:id, :name, :age, :job].each do |m| | |
define_method("find_by_#{m}") do |arg| | |
blk = ->usr { usr.send(m) == arg } | |
meth = [:id, :name].include?(m) ? :detect : :select | |
@@users.send(meth, &blk) | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add 'Charlie', 12, :programmer | |
add 'Ben', 17, :teacher | |
add 'Dick', 33, :lawyer | |
add 'Elizabeth', 23, :doctor | |
add 'Fernand', 27, :teacher | |
add 'George', 33, :programmer |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require_relative "user" | |
User.register | |
require "irb" | |
IRB.start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment