Jonathan
Jonathan

Reputation: 11494

Run custom bash function in Rails

I want to run my own function that I've put into my ~/.bashrc in Rails similar to how environment variables are called e.g. <%= ENV["EXAMPLE_VARIABLE"] %> ~ I will use it in a similar context.

I've read some popular questions on the subject (Calling Bash commands from Ruby; Execute Shell command from Ruby script) but I can't seem to put them to use.

I want to call a function that is loaded in my ~/.bashrc and return the value it returns. I've tried testing with irb but I keep getting no method found errors and don't really know what I'm doing.

Example function to test with:

#! /bin/bash

function get_custom_domain {
    echo localhost
}

Upvotes: 1

Views: 1005

Answers (1)

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

Bad practice use function in any rc files rc == run control when bash load, create separate .sh scripts and put in rails root dir(or any another) i use this way for my bash scripts:

in rails_root have script.sh must be executable (chmod +x script.sh):

#!/bin/bash
if [ $1 -eq "1" ]; then
  echo "Starting server";
  exit 0;
fi

if [ $1 -eq "2" ]; then
  echo "Time for sleep";
  exit 0;
fi

and call from app i use pure ruby object like executer:

 class Executer
   class << self

    def search_script(command)
      script = Dir['*.sh'].first
      if command == 1
        system("./#{script} #{command}")
      elsif command == 2
        system("./#{script} #{command}")
      end
     end

   end
 end

=> Executer.search_script(1)
=> # Starting server

I hope this example be helpful.

Upvotes: 1

Related Questions