lib/disposable/composition.rb in disposable-0.0.3 vs lib/disposable/composition.rb in disposable-0.0.4

- old
+ new

@@ -1,9 +1,10 @@ require 'forwardable' module Disposable # Composition delegates accessors to models as per configuration. + # # Composition doesn't know anything but methods (readers and writers) to expose and the mappings to # the internal models. Optionally, it knows about renamings such as mapping `#song_id` to `song.id`. # # class Album # include Disposable::Composition @@ -12,10 +13,12 @@ # end # # album = Album.new(cd: CD.find(1), band: Band.new) # album.id #=> 1 # album.title = "Ten Foot Pole" + # + # It allows accessing the contained models using the `#[]` reader. module Composition def self.included(base) base.extend(Forwardable) base.extend(ClassMethods) end @@ -24,23 +27,21 @@ module ClassMethods def map(options) @map = {} options.each do |mdl, meths| - attr_reader mdl - meths.each do |mtd| # [[:title], [:id, :song_id]] create_accessors(mdl, mtd) add_to_map(mdl, mtd) end end end private def create_accessors(model, methods) - def_instance_delegator model, *methods # reader - def_instance_delegator model, *methods.map { |m| "#{m}=" } # writer + def_instance_delegator "@#{model}", *methods # reader + def_instance_delegator "@#{model}", *methods.map { |m| "#{m}=" } # writer end def add_to_map(model, methods) name, public_name = methods public_name ||= name @@ -56,14 +57,19 @@ end @_models = models.values end + # Allows accessing the contained models. + def [](name) + instance_variable_get(:"@#{name}") + end + # Allows multiplexing method calls to all composed models. def each(&block) _models.each(&block) end private - attr_reader:_models + attr_reader :_models end end \ No newline at end of file