Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
.rvmrc
README.md
benchmarks.rb
cross_presenter.rb

README.md

Experiments while waiting for the train

Why?

Create agnostic presenters which can be used in Ruby templates, but also passed to JavaScript JSON encoded. Basically they are Structs instantiate with a hash of attributes, and that are able to convert themselves to hash/json.

The CrossPresenter.new method is explicitly defined like any other class method, and returns a class.

Another goal was having a class that could be instantiated like an OpenStruct (with a hash of attributes) but without the performance penalties (because the properties are not dynamically defined).

This...

BookPresenter = CrossPresenter.new(:id, :title)

...is the same as...

class BookPresenter < Struct.new(:id, :title)
  def initialize(attributes={})
    super(attributes[:id], attributes[:title])
  end

  def to_hash
    Hash[members.zip(entries)]
  end

  alias :as_json :to_hash
  alias :attributes :to_hash

  def to_json
    JSON::fast_generate(as_json)
  end
end

Well, almost, because in reality there is no need to create a subclass, we can just include new methods in the newly created class.

Once the presenter class is created...

book = BookPresenter.new(:id => 1, :title => "Title of the Book")

book.title == book[:title] == "Title of the Book"

book.attributes == book.to_hash == {:id=>1, :title=>"Title of the Book"}

book.to_json == '{"id":1,"title":"Title of the Book"}'
Something went wrong with that request. Please try again.