Ruby: How to Make a Public Static Method

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

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

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.

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

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

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

Ruby: Calling class method from instance

Rather than referring to the literal name of the class, inside an instance method you can just call self.class.whatever.

class Foo
def self.some_class_method
puts self
end

def some_instance_method
self.class.some_class_method
end
end

print "Class method: "
Foo.some_class_method

print "Instance method: "
Foo.new.some_instance_method

Outputs:


Class method: Foo
Instance method: Foo


Related Topics



Leave a reply



Submit