module Decor::ClassMethods

Public Instance Methods

version(version, &block) click to toggle source

Defines versions of the model's representation.

The `version` supplied is a string representation of the version. For example, `“v1”` represents version 1 of this model's representation.

The `version` is just a key, however, and any value works. Strings are convenient, especially in the form of `v1` or `v2010-12-09`.

If a block is provided, the block is treated as the body of the version's definition.

If a hash of `version => version_module` is passed in, we use your module instead of creating our own.

For example:

class Model
  include Decor

  version "v1" do
    # ...
  end

  module V20101209
    # ...
  end
  version "v2010-12-09" => V20101209

  # or use classes (for example) as version keys and alias to other
  # versions
  version AnotherModel  => "v1"
  version OtherModel    => V20101209

end
# File lib/decor.rb, line 120
def version(version, &block)
  case
  # Look up version module if no version block or module specified.
  #     version "v1" #=> #<Module>
  when self.versions.key?(version)
    return self.versions[version]
    
  # Define a new version from the block.
  #     version "v1" { ... }
  when block_given?
    constant = Module.new(&block)
    self.versions[version] = constant
    self
    
  # Set versions from a module, supports as many versions as passed in.
  #     version "v1"        => Version1,
  #             "v2"        => Version2,
  #             "v20101209" => "v2" # supports aliases
  else
    version.each do |(new_version, module_or_version)|
      self.versions[new_version] =
      if module_or_version.is_a?(Module)
        module_or_version
      else
        self.versions[module_or_version]
      end
    end
    
  end
  self
end