Skip to content

Instantly share code, notes, and snippets.

@melborne

melborne/user.rb

Created Aug 18, 2012
Embed
What would you like to do?
Inner DSL on Ruby sample?
#!/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
add 'Charlie', 12, :programmer
add 'Ben', 17, :teacher
add 'Dick', 33, :lawyer
add 'Elizabeth', 23, :doctor
add 'Fernand', 27, :teacher
add 'George', 33, :programmer
#!/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
You can’t perform that action at this time.