How do I create classes that I can use without using new
like Post.all
like ActiveRecord?
For example, by defining something for a class called Person
,
Person('yoshida').age
I'm thinking of using it in a way that I can.
Also, is there a name like this?Instanceless class.
ruby
Create a class method instead of an instance method.
class Post
def self.all
[1,2,3]
end
end
post.all
Ruby can do this if you write something like Post['ruby'].name
.
However, I believe that class design using method chains such as Post.find('ruby').name
is more Ruby-like.
class Post
attr_reader:name
def initialize (name)
@name = name
end
def self. [ ] (name )
new(name)
end
end
puts Post ["ruby"].name#=>ruby
Although it is not クラスsome definition for a class に, you can define a method with the same name apart from the class.
class Person
attr_accessor:name, :age
end
def Person (name)
person = Person.new
person.name = name
person.age = 20
person
end
pPerson('yoshida').age#=>20
If you want to define for a class (although the writing changes slightly), you can also define self.call
.
class Person 2
attr_accessor:name, :age
def self.call(name)
person = new
person.name = name
person.age = 30
person
end
end
# Need dot for call
pPerson2.('yoshida').age#=>30
579 Understanding How to Configure Google API Key
624 Uncaught (inpromise) Error on Electron: An object could not be cloned
618 GDB gets version error when attempting to debug with the Presense SDK (IDE)
925 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
577 Who developed the "avformat-59.dll" that comes with FFmpeg?
© 2024 OneMinuteCode. All rights reserved.