Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Entity Formatters #152

Closed
bobbytables opened this issue Mar 28, 2012 · 3 comments
Closed

Entity Formatters #152

bobbytables opened this issue Mar 28, 2012 · 3 comments

Comments

@bobbytables
Copy link
Contributor

I'd like to get some input on formatters for entities, I have an idea.

module Entities
  class User < Grape::Entity
    formatter :timestamp

    expose :name
    expose :created_at, :formatter => :timestamp

    private

    def timestamp(date)
      date.strftime('%m/%d/%Y')
    end
  end
end
@mbleigh
Copy link
Contributor

mbleigh commented Mar 28, 2012

I like the idea, at least in theory. Implementation wise here would be my suggestion:

Rather than declaring formatter methods, let's just have a :format_with option that works like so:

  1. If the option is set to a symbol, it does something like send(options[:format_with], value)
  2. If the option is not a symbol, it does options[:format_with].call(value)

This way you can create custom formatters as lambdas, custom classes, or anything in between. You can also just use simple method-based ones like your example above.

REVERSER = lambda{|value| value.reverse}

module Entities
  class User < Grape::Entity
    expose :name
    expose :created_at, :format_with => :timestamp
    expose :backwards_name, :format_with => REVERSER

    private

    def timestamp(date)
      date.strftime('%m/%d/%Y')
    end
  end
end

@mbleigh
Copy link
Contributor

mbleigh commented Mar 28, 2012

I'm not 100% sold on :format_with, maybe :formatter was better.

@bobbytables
Copy link
Contributor Author

Yeah I had the same thought on a lambda option as well. Although it would look odd if they supplied a block as well.

expose :created_at, :format_with => lambda {|d| d.strftime('%m/%d/%Y') } do |object,options|
end

I guess the options are:

  • It raises saying you have to do one or the other
  • The block is given the object after the formatter has had its way with it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants