Ben
Ben

Reputation: 3357

Include js code from file in Rails controller action

I have an action in a controller that sends an api call to a 3rd party app. Part of the payload is a js code in a string format that the app stores.

Here's an illustration:

def store_code_on_app
    myCode = "
        function hello(you){
            console.log("hello", you);
        }
    "

    RestClient.post(
    "http://theapp.com/codes/create",
        {
            code: myCode
        }
    )
end

Since my actual code is very long and to best manage multiple codes later on, I would like to store those codes in a file inside some folder in my rails app and call it from the controller. I would prefer to save the file with the appropriate extension (mycode.js) so it's easier to handle and debug.

How would you recommend I do that? Probably by requiring or including a file? perhaps in the lib folder?

Upvotes: 1

Views: 66

Answers (1)

rubyprince
rubyprince

Reputation: 17793

You could save it anywhere and load it using File.read if you dont want any dynamic content.

lib/something/code.js

function hello(you){
   console.log("hello", you);
}

controller

def store_code_on_app
    myCode = File.read("#{Rails.root}/lib/something/code.js")

    RestClient.post(
    "http://theapp.com/codes/create",
        {
            code: myCode
        }
    )
end

If it is dynamic, you could use render_to_string but I am not sure about this, but something along this line might work

app/views/shared_js_templates/code.js.erb

function <%= console_string %>(you){
  console.log("<%= console_string %>", you);
}

controller

def store_code_on_app
    myCode = render_to_string(
      'shared_js_templates/code.js.erb',
      layout: false,
      locals: { console_string: 'hello' }
    )

    RestClient.post(
    "http://theapp.com/codes/create",
        {
            code: myCode
        }
    )
end

With dynamic, you could do stuff like:

app/views/shared_js_templates/code.js.erb

<% 10.times do |index| %>
  function hello<%= index %>(you){
    console.log("hello<%= index %>", you);
  }
<% end %>

Upvotes: 2

Related Questions