Ruby on rails - Static method
To declare a static method, write ...
def self.checkPings
# A static method
end
... or ...
class Myclass extend self
def checkPings
# Its static method
end
end
Ruby: How to make a public static method?
Your given example is working very well
class Ask
def self.make_permalink(phrase)
phrase.strip.downcase.gsub! /\ +/, '-'
end
end
Ask.make_permalink("make a slug out of this line")
I tried in 1.8.7 and also in 1.9.3
Do you have a typo in you original script?
All the best
What is the use in class/static methods in ruby?
Your example isn't a good one.
Class methods might deal with managing all instances that exist of a class, and instance methods deal with a single instance at a time.
class Book
def self.all_by_author(author)
# made up database call
database.find_all(:books, where: { author: author }).map do |book_data|
new book_data # Same as: Book.new(book_data)
end
end
def title
@title
end
end
books = Book.all_by_author('Jules Vern')
books[0].title #=> 'Journey to the Center of the Earth'
In this example we have a class named Book
. It has a class method all_by_author
. It queries some pretend database and returns an array of Book
instances. The instance method title
fetches the title of a single Book
instance.
So the class method managing a collection of instances, and the instance method manages just that instance.
In general, if a method would operate on a group of instances, or is code related to that class but does not directly read or update a single instance, then it probably should be a class method.
access static method from controller instance variable
Is there a way in which I can make the model method cc(x) a static
method and call it from the instance variable of the controller
(@aaa)?
A static class method has to be called with the class object as the receiver, and an instance method has to be called with the instance method as the receiver.
Why do you care what type of method it is if you are going to call it with the instance?
Response to comment:
Then the instance that load() returns is not an instance of class A. It's very simple to test that what you want to do works: in one of your actions in your controller write:
@my_a = A.new
@my_a.do_stuff
Then in your model write:
class A
def do_stuff
logger.debug "do_stuff was called"
end
...
...
end
Then use the proper url, or click the proper link to make that action execute. Then look at the bottom of the file:
log/development.log
...and you will see a line that reads:
"do_stuff was called"
You can also record the type of the object that load() returns by writing:
def self.aa(params)
instance = load
logger.debug instance.class #<===ADD THIS LINE
instance.state_a = {:xx => params[:x]...}
instance
end
Ruby class with static method calling a private method?
First off, static
is not really part of the Ruby jargon.
Let's take a simple example:
class Bar
def self.foo
end
end
It defines the method foo
on an explicit object, self
, which in that scope returns the containing class Bar
.
Yes, it can be defined a class method, but static does not really make sense in Ruby.
Then private
would not work, because defining a method on an explicit object (e.g. def self.foo
) bypasses the access qualifiers and makes the method public.
What you can do, is to use the class << self
syntax to open the metaclass of the containing class, and define the methods there as instance methods:
class Foo
class << self
def bar
do_calc
end
def baz
do_calc
end
private
def do_calc
puts "calculating..."
end
end
end
This will give you what you need:
Foo.bar
calculating...
Foo.baz
calculating...
Foo.do_calc
NoMethodError: private method `do_calc' called for Foo:Class
Can not call method of other class from static method
NameError means the your SendMailTask
isn't loaded. so you will have to load that. so couple of things.
I noticed a typo
workes
, so please verify the file name is correct. By Convention, it should be located atapp/workers/send_mail_task.rb
. so kindly double-triple check the same.About
require './SendMailTask'
, this is wrong. Instead it would besend_mail_task
as requires works on filenames & not class names.if still get an error, then please post your
$LOAD_PATH
to see you are requiring the file relative to the defined$LOAD_PATH
Instead of
require
, I prefer to userequire_dependency
as it works with code-reloading etc. so if you have trouble with auto-loading, just stick that require_dependency on top of the file, this will hint rails to load the file BEFORE running the controller.
Delegate static methods with Ruby on Rails?
class MyThing
class << self
delegate :some_static_method, :to => :User
end
end
How should I call object methods from a static method in a ruby class?
Personally I would probably do something like:
class MyUtil
API_KEY = "mykey"
def apiClient
@apiClient
end
def initialize
@apiClient = Vendor::API::Client.new(API_KEY)
yield self if block_given?
end
class << self
def setUpSomthing(arg1,arg2,arg3=nil)
self.new do |util|
#setup logic goes here
end
end
def api_call(arg1,arg2,arg3)
util = setUpSomthing(arg1,arg2,arg3)
util.apiClient.call("foo", param2)
#do other stuff
end
end
end
The difference is subtle but in this version setUpSomthing
guarantees a return of the instance of the class and it's more obvious what you're doing.
Here setUpSomthing
is responsible for setting up the object and then returning it so it can be used for things, this way you have a clear separation of creating the object and setting the object up.
How do I alias a static method in Ruby?
Static methods are really instance methods of class's eigenclass, so you can do:
class << self
def minutes
(rand(58) + 1).to_s
end
def hours
(rand(22) + 1).to_s
end
alias :seconds :minutes
end
Related Topics
How to Remove '---' on Top of a Yaml File
How to Get Past "Http://Gems.Rubyforge.Org/ Does Not Appear to Be a Repository" Error Message
Ruby Gem Dependencies on Offline Server
Difference Between Downcase and Downcase! in Ruby
How to Use Savon Nested Attributes! Hash
How to Test If Parameters Exist in Rails
How to Run a Ruby File in a Rails Environment
What Is the Best Practice When It Comes to Testing "Infinite Loops"
How to Find Out Who Is Connected to Actioncable
Converting a Hexadecimal Digest to Base64 in Ruby
What Is the Ruby Equivalent of Python's Getattr
How to Improve Jruby Load Time