Passing options to template function in thor
Asked Answered
L

2

11

I am looking for a way to pass options to the ERB templating engine in thors template action.

I stumbled upon the bundler cli source where thors template action is being used like this:

opts = {:name => name, 
    :constant_name => constant_name, 
    :constant_array => constant_array, 
    :author_name => author_name, 
    :author_email => author_email
}

template(File.join("newgem/Gemfile.tt"),
           File.join(target, "Gemfile"),
            opts)

But when I add options like this in my thor tasks they are not found by ERB, i can only use arguments and functions in my thor class to set variables in the template.

I have no clue how binding works in ruby, maybe there is a way to pass a scope through binding to ERB.

Lintwhite answered 27/6, 2011 at 19:43 Comment(2)
What code did you try in your Thor file that didn't work?Wino
I did copy the code above and it didn't catch the passed options.Lintwhite
E
14

By using instance variables, it should work.

@name = name
template("source","target")

My template looks like this:

<test><%= @name %></test>

This works for me. I haven't tried the passing of specific values.

Extant answered 9/9, 2011 at 12:36 Comment(0)
G
12

I can't find any documentation to answer this, but reading through the source of the Bundler CLI, it appears that if you were trying to reference the :author_email parameter inside the template,

Author email: <%= config[:author_email] %>

works.

Gravelblind answered 29/9, 2011 at 20:35 Comment(1)
This work for me too. The hash of opts passed to template is called config in the Erb template.Exerciser

© 2022 - 2024 — McMap. All rights reserved.