Skip to content

Instantly share code, notes, and snippets.

@justinko
Created December 16, 2010 14:37
Show Gist options
  • Save justinko/743458 to your computer and use it in GitHub Desktop.
Save justinko/743458 to your computer and use it in GitHub Desktop.
Common gem configuration implementations
class MyGem
class << self
attr_accessor :color
end
def self.configure(&block)
instance_eval(&block)
end
end
MyGem.configure do
self.color = true
end
puts MyGem.color # => true
Object.send(:remove_const, :MyGem)
########################################
class MyGem
def self.configure
yield configuration
end
def self.configuration
@configuration ||= Configuration.new
end
class Configuration
attr_accessor :color
end
end
MyGem.configure do |config|
config.color = true
end
puts MyGem.configuration.color # => true
Object.send(:remove_const, :MyGem)
########################################
class MyGem
def self.configure
yield configuration
end
def self.configuration
@configuration ||= Configuration.new
end
class Configuration
def initialize
@fields = Fields.new
end
def fields(&block)
if block
@fields.instance_eval(&block)
else
@fields.to_pretty
end
end
class Fields
def initialize
@fields = []
end
def to_pretty
{}.tap do |pretty|
@fields.each do |field|
pretty[field.name] = {:columns => field.columns}
end
end.inspect
end
def method_missing(sym, *args, &block)
@fields << Field.new(sym, &block)
end
class Field
attr_reader :name, :columns
def initialize(name, &block)
@name = name
@block = block
@columns = []
set_columns
end
def column(name)
@columns << name
end
def set_columns
instance_eval(&@block) if @block
end
end
end
end
end
MyGem.configure do |config|
config.fields do
dog :canine
cat :feline
rat :rodent do
column :birthdate
column :food_type
end
end
end
puts MyGem.configuration.fields # =>
# {
# :dog => { :columns => [] },
# :cat => { :columns => [] },
# :rat => { :columns => [:birthdate, :food_type] }
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment