如何在Rails应用程序之外使用JBuilder?

时间:2012-05-16 16:27:50

标签: ruby-on-rails json gem jbuilder

我喜欢JBuilder的语法,并希望在rails之外使用它。我有一个类和一个to_json方法:

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

不幸的是我得到了:

/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)>'

对应于:

# 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))
  # .... 

知道我需要宝石中的宝石来满足JBuilder吗?

1 个答案:

答案 0 :(得分:0)

您可以使用

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