uguMark
uguMark

Reputation: 611

Is it possible to run rails console commands in ruby controller/view and display the output

Example I want to create a dropdown of commands in an admin section. When the user selects one, such as

Purchase.all

User.where(:active => 1)

Basically any common commands that I would run in the console before a fully functional backend is created. I know this is a bit unconventional but im just looking for a rapid way to make some common admin queries available. Once the command has been run I'd like it display the exact output that would be displayed in the rails console. I've installed the Hirb gem which formats results in the console and would like that formatting to show when I output it in the view. Is this at all achievable?

Upvotes: 0

Views: 338

Answers (1)

Stefan
Stefan

Reputation: 114248

Of course it is possible, just run the command in your action, render it with Hirb and pass the output to your view:

def action
  result = run_command(params[:command])

  Hirb::View.load_config
  Hirb::View.render_method = lambda { |output| @hirb_output = output }
  Hirb::View.render_output(result)
end

private

def run_command(command)
  case command
  when 'purchase_all'
    Purchase.all
  when 'active_users'
    User.where(:active => 1)
  end
end

And in your view:

<pre>
  <%= @hirb_output %>
</pre>

However, I would use ActiveAdmin or RailsAdmin instead.

Upvotes: 2

Related Questions