listing out available variables in an ERB template

Discussion in 'Ruby' started by mgerstenblatt@gmail.com, Sep 27, 2010.

  1. Guest

    [Note: parts of this message were removed to make it a legal post.]

    Hi All,

    Suppose I have a Ruby ERB template named **my_template.html.erb**, and it
    contains the following:

    <div><%= @div_1 %></div>
    <div><%= @div_2 %></div>
    <div><%= @div_3 %></div>

    Is there a way I can programatically list out all the available variables in
    the template?

    For example, the following method:

    def list_out_variables
    template = File.open("path_to/my_template.html.erb", "rb").read
    erb = ERB.new( template )
    erb.this_method_would_list_out_variables
    end

    would return something like:

    ['div1','div2','div3']


    Any help would be greatly appreciated.

    Thanks,
    Mike
     
    , Sep 27, 2010
    #1
    1. Advertising

  2. Josh Cheek Guest

    [Note: parts of this message were removed to make it a legal post.]

    On Sun, Sep 26, 2010 at 8:12 PM, <
    > wrote:

    > Hi All,
    >
    > Suppose I have a Ruby ERB template named **my_template.html.erb**, and it
    > contains the following:
    >
    > <div><%= @div_1 %></div>
    > <div><%= @div_2 %></div>
    > <div><%= @div_3 %></div>
    >
    > Is there a way I can programatically list out all the available variables
    > in
    > the template?
    >
    > For example, the following method:
    >
    > def list_out_variables
    > template = File.open("path_to/my_template.html.erb", "rb").read
    > erb = ERB.new( template )
    > erb.this_method_would_list_out_variables
    > end
    >
    > would return something like:
    >
    > ['div1','div2','div3']
    >
    >
    > Any help would be greatly appreciated.
    >
    > Thanks,
    > Mike
    >



    Ruby has some reflexive methods you can use.


    $gvar = 1
    lvar = 2
    @ivar = 3
    class Foo
    @@cvar = 4
    end

    p instance_variables
    p global_variables
    p local_variables
    class Foo
    p class_variables
    end
     
    Josh Cheek, Sep 27, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Steve V
    Replies:
    6
    Views:
    249
    Steve V
    Apr 20, 2005
  2. Aaron Smith

    ERB question, not seeing variables..

    Aaron Smith, Jul 21, 2007, in forum: Ruby
    Replies:
    2
    Views:
    107
    Aaron Smith
    Jul 21, 2007
  3. Jacob Lichner
    Replies:
    2
    Views:
    125
    Jacob Lichner
    Sep 3, 2009
  4. Brian Candler
    Replies:
    2
    Views:
    804
    Brian Candler
    Oct 14, 2010
  5. Dan Thomas

    link to .erb file, from .erb file

    Dan Thomas, Jan 26, 2011, in forum: Ruby
    Replies:
    4
    Views:
    176
    Dan Thomas
    Jan 26, 2011
Loading...

Share This Page