How to use JBuilder outside of Rails app?

912 Views Asked by At

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?

1

There are 1 best solutions below

0
On

You can use

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