Skip to content

Arbre helper for Rails #38

Description

@timoschilling

Example written from @seanlinsley on activeadmin/activeadmin#2874:

# app/helpers/application_helper.rb
module ApplicationHelper
  def arbre(&block)
    Arbre::Context.new(&block).to_s
  end
end

# app/decorators/foo_decorator.rb
class FooDecorator < Draper::Decorator
  def wheelchair
    arbre do
      status_tag model.wheelchair, class: model.wheelchair
    end
  end
end

The other option is to use a preinitialised instance that be dup for each call:

module ApplicationHelper
  def arbre_context
    @arbre_context ||= Arbre::Context.new
    @arbre_context.dup
  end

  def arbre(&block)
    arbre_context.instance_eval(&block).to_s
  end
end

dup is ~3 times faster that new

context = Arbre::Context.new
Benchmark.ips do |b|
  b.config(:time => 5, :warmup => 2)
  b.report("dup"){ context.dup }
  b.report("new"){ Arbre::Context.new }
  b.compare!
end
Calculating -------------------------------------
                 dup      1110 i/100ms
                 new      1026 i/100ms
-------------------------------------------------
                 dup   819778.0 (±10.9%) i/s -    3751800 in   4.650747s
                 new   284126.6 (±8.3%) i/s -    1367658 in   4.851749s

Comparison:
                 dup:   819778.0 i/s
                 new:   284126.6 i/s - 2.89x slower

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions