简体   繁体   中英

How to use JBuilder outside of Rails app?

I love JBuilder's syntax, and would like to use it outside of rails. I have a class and and a to_json method:

class Blog

  def to_json
    Jbuilder.encode do |json|
      json.(self, :id, :logo)

      json.articles articles do |json, article|
        json.id article.id
      end
    end
  end

end

Unfortunately I'm getting:

/Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/jbuilder-0.4.0/lib/jbuilder.rb:13:in `define_method': wrong argument type NilClass (expected Proc/Method) (TypeError)
  from /Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/jbuilder-0.4.0/lib/jbuilder.rb:13:in `<class:Jbuilder>'
  from /Users/justin/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/jbuilder-0.4.0/lib/jbuilder.rb:7:in `<top (required)>'

Which corresponds to:

# jbuilder.rb
class Jbuilder < BlankSlate
  # Yields a builder and automatically turns the result into a JSON string
  def self.encode
    new._tap { |jbuilder| yield jbuilder }.target!
  end

  define_method(:__class__, find_hidden_method(:class))   # <--- exception
  define_method(:_tap, find_hidden_method(:tap))
  # .... 

Any idea what gems I need to require in the gem to satisfy JBuilder?

You can use

template = File.read(template_file)
output = Jbuilder.encode { |json| eval template }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM