How to create a custom method for the rails console?
Just put it in the ~/.irbrc
file. It gets loaded every time you run irb
or rails console
. The Rails console is just irb
with your Rails application environment loaded.
Find more infos about irb
here: http://ruby-doc.com/docs/ProgrammingRuby/html/irb.html#S2
How to create a custom method for my rails model
It seems like all good, just reload your rails console. Rails does not apply changes in your classes immediately.
Defining custom methods within a model/class in Rails 4
Creating method log
Say you have a class User
, and within the class, you define the method has_cell_phone
. (The contents of that method does not matter.) When you define a method in a class as def has_cell_phone
, that method can be called on any User
object. While the class User
is itself a class object, you would call it on an object whose immediate class is User
. In correct terms, you would be writing an instance method for an instance of the User
class.
You are getting that error because the method log
you defined works only for an _instance of the ActivityLog
class. If you do the following, you can call log
correctly, given your current code:
activity_log = ActivityLog.create # with required params
activity_log.log
Secondly, you are calling log
with parameters, while your method definition does not require any. (That would look like def log(params)
.)
Now, here is where you modify your existing code. When you want to call a method on the entire class (meaning the class itself), you prepend the keyword self
to the class-method definition. For example, for the User
class, it would be def self.create_user_with_cell_phone
. You can also add arguments to that method. The arguments you provide in your "method call" line, I would add those to your class method, like so:
def self.log(instance_id, action)
# ...
end
ActivityLog.log(1, 'create')
You would not need to include the user_id
, because, based on your logic, it checks if the current_user
object is true
, and follows from there.
Creating a class constant
A second look at your question, I found that you are defining a method actions
. Remember what I said about instance methods? Since it appears that actions
will always remain constant, I recommend that you make it one! To do so, it's recommended you place the following line in your class, before any method definitions.
ACTIONS = ['start','stop','create','destroy']
Then, any time you want to call ACTIONS
while inside the ActivityLog
class, you do the following: ACTIONS.index(action)
. If you want to call this constant outside of its class, you would do this: ActivityLog::ACTION
. It is similar syntax to a class-method call, instead you use ::
to separate the class from the constant. Re-examining your code, it should now look like this:
class ActivityLog < ActiveRecord::Base
ACTIONS = ['start','stop','create','destroy']
validates :user_id, :instance_id, :action, presence: true
validates :user_id, :instance_id, :action, numericality: true
def self.log(instance_id, action)
ActivityLog.create(
user_id: (current_user ? current_user.id : -1),
instance_id: instance_id,
action: ACTIONS.index(action)
)
end
end
How to make a custom method available in Pry console
In your home directory (~
), you can create a file named .pryrc
and put a Ruby function in it:
def my_stack(app_name = '')
caller.select {|line| line.include? app_name }
end
And you can use my_stack
or my_stack('myapp')
from Pry.
Calling model custom method in controller
Change the class method:
def self.add_manager(params)
To an instance method:
def add_manager(params)
as @rally is an instance of your Rally class
(answered in comments above - removing from unanswered list)
How to make a custom method that can be used anywhere in rails app
Reading the comments it seems like you are just looking for a clear and simple example of a method that is available everywhere in your application:
# in app/models/calculator.rb
module Calculator
def self.plus_two(x)
x + 2
end
end
Which can be called like this:
Calculator.plus_two(8)
#=> 10
Rails creating a simple function to run in console for system wide
In case you would like to run custom methods in Rails specifically, you can define you helper methods in a module in lib
directory
# lib/custom_console_methods.rb
module CustomConsoleMethods
def ping
puts 'pong'
end
end
Then in the application.rb
file, pass a block to console
that includes your module into Rails::ConsoleMethods
# config/application.rb
module YourRailsApp
class Application < Rails::Application
console do
require 'custom_console_methods'
Rails::ConsoleMethods.include(CustomConsoleMethods)
end
end
end
If you would like to run it in system wide, just put the methods in ~/.irbrc
file. It gets loaded every time you run irb
or rails console
def ping
puts 'pong'
end
How to call custom method in ruby on rails 4?
I'd suggest to move it to your model:
question.rb
def self.ping
question = Question.first
question.update(:amplify => question.amplify + 1)
end
and define custom route, routes.rb
post '/ping' => 'questions#ping', as: 'ping'
questions_controller.rb
def ping
Question.ping
end
then you can reference it from console:
Question.ping
How to store macros in rails console?
well. not actually macros but we have dynamic_method define right.
so u can do this in your rails console:
define_method :bar do
Apartment::Tenant.switch
end
and then you can call bar
method as short for your method.
To add it in initializers
i have created one file say bar.rb
in initializers folder.
then I have done it , I don't if its ideal:
class Object
def bar
Apartment::Tenant.switch
end
end
restart you console and call bar
Custom extensions for Rails console
You can define helper functions in the file ~/.irbrc. This will affect all of your irb sessions, not just rails console sessions, so you may have to conditionally execute some helpers:
if defined? Rails
[helper code here...]
end
Related Topics
Why Is the Splat Used Inside an Array Definition Here
Error Creating Rails Db Using Rake Db:Create
Scraping an Angularjs Application
Why Does 'Puts(Nil or 4)' Fail in Ruby
How to Enable Colors with Rspec When Using Jruby or Bundle Exec
Require Command Not Working Within Bash Irb on Snow Leopard
Ruby Installation (2.2.2) Fails in MACos Big Sur
In Ruby How to Tell If a String Input Is in Uppercase or Lowercase
Getting Count of Elements by 'Created_At' by Day in a Given Month
Fast-Stemmer Installation Problems
Rails Gem to Break a Paragraph into Series of Sentences
Gets.Chomp Without Moving to a New Line
Show Markers on Google Maps Dynamically -Rails 3.2
How to Upload a JSON File with Secret Keys to Heroku
How to Render a Layout Directly from Routes.Rb, Without a Controller
Upgrade Ruby on Elastic Beanstalk
Ruby's Argv Can Be Empty on Windows Depending on a Way to Run Script