To define a class I must do the following (for example)
class Foo
#attr_accessors
#methods
#so on
end
foo = Foo.new #to create an instance
Problem
I need to achieve the following
case_class Foo_inmutable #I change class for case_class
#attr_accessors
#methods
#so on
end
foo_inmutable = Foo_inmutable.new
#->SyntaxError: uninitialze constant Foo_inmutable
I need the ruby interpreter to treat the case_class the same way to keyword class
Like almost all programming languages, Ruby does not allow you to modify its syntax or semantics. So, what you want is not possible.
You can, however, quite easily write a method that accomplishes your goal, but without changing the syntax and semantics of Ruby:
class Module
def case_class(name, superclass = ::Object, &blk)
const_set(name, Class.new(superclass, &blk))
end
end
def case_class(name, superclass = ::Object, &blk)
self.class.case_class(name, superclass, &blk)
end
case_class :Foo_immutable do
# ↑ ↑↑
# these are the only differences to your proposed syntax
#attr_accessors
#methods
#so on
end
foo_immutable = Foo_immutable.new
To achieve this, besides defining what's already been said in the previous answer:
class Module
def case_class(name, superclass = ::Object, &blk)
const_set(name, Class.new(superclass, &blk))
end
end
def case_class(name, superclass = ::Object, &blk)
self.class.case_class(name, superclass, &blk)
end
You may want to have a look at the const_missing method, and the "Lookup" that ruby does for constants inside the various scopes
That will allow you to do stuff like
case_class Foo do
...
end
For further explanation you can refer to this page: tadp-utn-frba.github.io
It has tons of useful scripts explaining ruby metaprogramming (in spanish) and how to achieve what you are looking for, also it has contact references for the
people in charge of the page, so you can email them at any time (Given you are a student of the class) for academic reasons.
Cheers!
Related
Trying to make sense of this 'refinements' business.
I'm making a module which refines a core class:
module StringPatch
refine String do
def foo
true
end
end
end
Then a class to use the refinement
class PatchedClass
end
PatchedClass.send :using, StringPatch
I get this error:
RuntimeError: Module#using is not permitted in methods
How can I make this work?
I am trying to dynamically patch core classes in a certain scope only. I want to make the patches available in the class and instance scope.
As far as I know, the refinement is active until the end of the script when using is in main, and until the end of the current Class/Module definition when using is in a Class or Module.
module StringPatch
refine String do
def foo
true
end
end
end
class PatchedClass
using StringPatch
puts "test".foo
end
class PatchedClass
puts "test".foo #=> undefined method `foo' for "test":String (NoMethodError)
end
This would mean that if you manage to dynamically call using on a Class or Module, its effect will be directly removed.
You cannot use refine in methods, but you can define methods in a Class that has been refined :
class PatchedClass
using StringPatch
def foo
"test".foo #=> true
end
end
class PatchedClass
def bar
"test".foo
end
end
patched = PatchedClass.new
puts patched.foo #=> true
puts patched.bar #=> undefined method `foo' for "test":String (NoMethodError)
For your questions, this discussion could be interesting. It looks like refinements are restricted on purpose, but I don't know why :
Because refinement activation should be as static as possible.
Refinements are strictly scoped and can't be used dynamically as it stands. I get around this by structuring modules such that I can use them a refinement or as a monkey patch when needed. There are still limitations to this approach, and with refinements in general, but still handy.
module StringPatch
def foo
true
end
refine String do
include StringPatch
end
end
Used as a refinement
class PatchedClass
using StringPatch
end
Used as a single instance patch
obj = PatchedClass.new
obj.extend(StringPatch)
You can of course also extend the whole class as a monkey patch but then you pollute the class forever and for all eternity.
PatchedClass.prepend(StringPatch)
I appreciate the other answers but I think I have to add my own.
It seems there's very little leeway with using - the error that it can't be used in methods is serious. The best wiggle room I found is to iteratively call it, passing a variable as argument.
So if I have two patch classes, I can make a constant Patches, a list that includes both. Then in the class/module I want to load the patches, I can run the iterative using.
module StringPatch
refine String do
def patch; :string_patch; end
end
end
module HashPatch
refine Hash do
def patch; :hash_patch; end
end
end
Patches = [StringPatch, HashPatch]
class C
Patches.each { |x| using x }
def self.test
[''.patch, {}.patch]
new.test
end
def test
[''.patch, {}.patch]
end
end
C.test
The using does make the patches available in both instance and class scope.
The limitation is that there is no way to abstract away the using call.
I can't say Patches.each &method(:using)
or move Patches.each { |x| using x } to a method,
or use eval "Patches.each { |x| using x}"
I'm trying to make a DSL like configuration for classes that include a module but to have the configured variable available to both class and instance methods seems to require littering the module with access methods. Is there a more elegant way to do this?
module DogMixin
class << self
def included(base)
base.extend ClassMethods
end
end
module ClassMethods
def breed(value)
#dog_breed = value
end
def dog_breed
#dog_breed
end
end
end
class Foo
include DogMixin
breed :havanese
end
puts Foo.dog_breed
# not implemented but should be able to do this as well
f = Foo.new
f.dog_breed
Your example is a bit weird I think :)
Anyway, one way to avoid writing the accessors (the assignment - accessor is problematic in my eyes - especially in the given example) is to define constants, as in the example below. If however you need runtime-assignments, please edit your question (and thus render this answer invalid :) except you want to mess with runtime constant assignment, which is possible but messy).
module DogMixin
# **include** DogMixin to get `Class.dog_breed`
class << self
def included(base)
def base.dog_breed
self::DOG_BREED || "pug"
end
end
end
# **extend** DogMixin to get `instance.dog_breed`
def dog_breed
self.class.const_get(:DOG_BREED) || "pug"
end
end
class Foomer
DOG_BREED = 'foomer'
extend DogMixin
include DogMixin
end
f = Foomer.new
puts Foomer.dog_breed
puts f.dog_breed
# If I understand you correctly, this is the most important (?):
f.dog_breed == Foomer.dog_breed #=> true
It took some reading of (In Ruby) allowing mixed-in class methods access to class constants to get the Instance-And-Class Constant lookup from a module, but it works. I am not sure if I really like the solution though. Good question, although you could add a little detail.
I have an app that includes modules into core Classes for adding client customizations.
I'm finding that class_eval is a good way to override methods in the core Class, but sometimes I would like to avoid re-writing the entire method, and just defer to the original method.
For example, if I have a method called account_balance, it would be nice to do something like this in my module (i.e. the module that gets included into the Class):
module CustomClient
def self.included base
base.class_eval do
def account_balance
send_alert_email if balance < min
super # Then this would just defer the rest of the logic defined in the original class
end
end
end
end
But using class_eval seems to take the super method out of the lookup path.
Does anyone know how to work around this?
Thanks!
I think there are several ways to do what you're wanting to do. One is to open the class and alias the old implementation:
class MyClass
def method1
1
end
end
class MyClass
alias_method :old_method1, :method1
def method1
old_method1 + 1
end
end
MyClass.new.method1
=> 2
This is a form of monkey patching, so probably best to make use of the idiom in moderation. Also, sometimes what is wanted is a separate helper method that holds the common functionality.
EDIT: See Jörg W Mittag's answer for a more comprehensive set of options.
I'm finding that instance_eval is a good way to override methods in the core Class,
You are not overriding. You are overwriting aka monkeypatching.
but sometimes I would like to avoid re-writing the entire method, and just defer to the original method.
You can't defer to the original method. There is no original method. You overwrote it.
But using instance_eval seems to take the super method out of the lookup path.
There is no inheritance in your example. super doesn't even come into play.
See this answer for possible solutions and alternatives: When monkey patching a method, can you call the overridden method from the new implementation?
As you say, alias_method must be used carefully. Given this contrived example :
module CustomClient
...
host.class_eval do
alias :old_account_balance :account_balance
def account_balance ...
old_account_balance
end
...
class CoreClass
def old_account_balance ... defined here or in a superclass or
in another included module
def account_balance
# some new stuff ...
old_account_balance # some old stuff ...
end
include CustomClient
end
you end up with an infinite loop because, after alias, old_account_balance is a copy of account_balance, which now calls itself :
$ ruby -w t4.rb
t4.rb:21: warning: method redefined; discarding old old_account_balance
t4.rb:2: warning: previous definition of old_account_balance was here
[ output of puts removed ]
t4.rb:6: stack level too deep (SystemStackError)
[from the Pickaxe] The problem with this technique [alias_method] is that you’re relying on there not being an existing method called old_xxx. A better alternative is to make use of method objects, which are effectively anonymous.
Having said that, if you own the source code, a simple alias is good enough. But for a more general case, i'll use Jörg's Method Wrapping technique.
class CoreClass
def account_balance
puts 'CoreClass#account_balance, stuff deferred to the original method.'
end
end
module CustomClient
def self.included host
#is_defined_account_balance = host.new.respond_to? :account_balance
puts "is_defined_account_balance=#{#is_defined_account_balance}"
# pass this flag from CustomClient to host :
host.instance_variable_set(:#is_defined_account_balance,
#is_defined_account_balance)
host.class_eval do
old_account_balance = instance_method(:account_balance) if
#is_defined_account_balance
define_method(:account_balance) do |*args|
puts 'CustomClient#account_balance, additional stuff'
# like super :
old_account_balance.bind(self).call(*args) if
self.class.instance_variable_get(:#is_defined_account_balance)
end
end
end
end
class CoreClass
include CustomClient
end
print 'CoreClass.new.account_balance : '
CoreClass.new.account_balance
Output :
$ ruby -w t5.rb
is_defined_account_balance=true
CoreClass.new.account_balance : CustomClient#account_balance, additional stuff
CoreClass#account_balance, stuff deferred to the original method.
Why not a class variable ##is_defined_account_balance ? [from the Pickaxe] The module or class definition containing the include gains access to the constants, class variables, and instance methods of the module it includes.
It would avoid passing it from CustomClient to host and simplify the test :
old_account_balance if ##is_defined_account_balance # = super
But some dislike class variables as much as global variables.
[from the Pickaxe] The method Object#instance_eval lets you set self to be some arbitrary object, evaluates the code in a block with, and then resets self.
module CustomClient
def self.included base
base.instance_eval do
puts "about to def account_balance in #{self}"
def account_balance
super
end
end
end
end
class Client
include CustomClient #=> about to def account_balance in Client
end
As you can see, def account_balance is evaluated in the context of class Client, the host class which includes the module, hence account_balance becomes a singleton method (aka class method) of Client :
print 'Client.singleton_methods : '
p Client.singleton_methods #=> Client.singleton_methods : [:account_balance]
Client.new.account_balance won't work because it's not an instance method.
"I have an app that includes modules into core Classes"
As you don't give much details, I have imagined the following infrastructure :
class SuperClient
def account_balance
puts 'SuperClient#account_balance'
end
end
class Client < SuperClient
include CustomClient
end
Now replace instance_eval by class_eval. [from the Pickaxe] class_eval sets things up as if you were in the body of a class definition, so method definitions will define instance methods.
module CustomClient
...
base.class_eval do
...
print 'Client.new.account_balance : '
Client.new.account_balance
Output :
#=> from include CustomClient :
about to def account_balance in Client #=> as class Client, in the body of Client
Client.singleton_methods : []
Client.new.account_balance : SuperClient#account_balance #=> from super
"But using instance_eval seems to take the super method out of the lookup path."
super has worked. The problem was instance_eval.
I found a blog post on alias vs. alias_method. As shown in the example given in that blog post, I simply want to alias a method to another within the same class. Which should I use? I always see alias used, but someone told me alias_method is better.
Usage of alias
class User
def full_name
puts "Johnnie Walker"
end
alias name full_name
end
User.new.name #=>Johnnie Walker
Usage of alias_method
class User
def full_name
puts "Johnnie Walker"
end
alias_method :name, :full_name
end
User.new.name #=>Johnnie Walker
Blog post link here
alias_method can be redefined if need be. (it's defined in the Module class.)
alias's behavior changes depending on its scope and can be quite unpredictable at times.
Verdict: Use alias_method - it gives you a ton more flexibility.
Usage:
def foo
"foo"
end
alias_method :baz, :foo
Apart from the syntax, the main difference is in the scoping:
# scoping with alias_method
class User
def full_name
puts "Johnnie Walker"
end
def self.add_rename
alias_method :name, :full_name
end
end
class Developer < User
def full_name
puts "Geeky geek"
end
add_rename
end
Developer.new.name #=> 'Geeky geek'
In the above case method “name” picks the method “full_name” defined in “Developer” class. Now lets try with alias.
class User
def full_name
puts "Johnnie Walker"
end
def self.add_rename
alias name full_name
end
end
class Developer < User
def full_name
puts "Geeky geek"
end
add_rename
end
Developer.new.name #=> 'Johnnie Walker'
With the usage of alias the method “name” is not able to pick the method “full_name” defined in Developer.
This is because alias is a keyword and it is lexically scoped. It means it treats self as the value of self at the time the source code was read . In contrast alias_method treats self as the value determined at the run time.
Source: http://blog.bigbinary.com/2012/01/08/alias-vs-alias-method.html
A point in favor of alias instead of alias_method is that its semantic is recognized by rdoc, leading to neat cross references in the generated documentation, while rdoc completely ignore alias_method.
I think there is an unwritten rule (something like a convention) that says to use 'alias' just for registering a method-name alias, means if you like to give the user of your code one method with more than one name:
class Engine
def start
#code goes here
end
alias run start
end
If you need to extend your code, use the ruby meta alternative.
class Engine
def start
puts "start me"
end
end
Engine.new.start() # => start me
Engine.class_eval do
unless method_defined?(:run)
alias_method :run, :start
define_method(:start) do
puts "'before' extension"
run()
puts "'after' extension"
end
end
end
Engine.new.start
# => 'before' extension
# => start me
# => 'after' extension
Engine.new.run # => start me
A year after asking the question comes a new article on the subject:
http://erniemiller.org/2014/10/23/in-defense-of-alias/
It seems that "so many men, so many minds." From the former article author encourages to use alias_method, while the latter suggests using alias.
However there's a common overview of these methods in both blogposts and answers above:
use alias when you want to limit aliasing to the scope where it's defined
use alias_method to allow inherited classes to access it
The rubocop gem contributors propose in their Ruby Style Guide:
Prefer alias when aliasing methods in lexical class scope as the
resolution of self in this context is also lexical, and it
communicates clearly to the user that the indirection of your alias
will not be altered at runtime or by any subclass unless made
explicit.
class Westerner
def first_name
#names.first
end
alias given_name first_name
end
Always use alias_method when aliasing methods of modules, classes, or
singleton classes at runtime, as the lexical scope of alias leads to
unpredictability in these cases
module Mononymous
def self.included(other)
other.class_eval { alias_method :full_name, :given_name }
end
end
class Sting < Westerner
include Mononymous
end
alias_method new_method, old_method
old_method will be declared in a class or module which is being inherited now to our class where new_method will be used.
these can be variable or method both.
Suppose Class_1 has old_method, and Class_2 and Class_3 both of them inherit Class_1.
If, initialization of Class_2 and Class_3 is done in Class_1 then both can have different name in Class_2 and Class_3 and its usage.
Learning ruby. I'm under the impression that boolean attributes should be named as follows:
my_boolean_attribute?
However, I get syntax errors when attempting to do the following:
class MyClass
attr_accessor :my_boolean_attribute?
def initialize
:my_boolean_attribute? = false
end
end
Apparently ruby is hating the "?". Is this the convention? What am I doing wrong?
Edit: three-years later; the times, they are a-changin'…
Julik's answer is the simplest and best way to tackle the problem these days:
class Foo
attr_accessor :dead
alias_method :dead?, :dead # will pick up the reader method
end
My answer to the original question follows, for posterity…
The short version:
You can't use a question mark in the name of an instance variable.
The longer version:
Take, for example, attr_accessor :foo — it's simply conceptually a bit of syntactic sugar for the following:
def foo
#foo
end
def foo=(newfoo)
#foo = newfoo
end
Furthermore, the question-mark suffix is mostly just a convention to indicate that the return value of a method is a boolean.
The best approximation I can make of what you're going for here…
class MyClass
def initialize
#awesome = true
end
def awesome?
#awesome
end
end
In this case, there may be a case to be made for using attr_accessor — after all, it may be explicit that you're working directly with a boolean attribute. Generally, I save the question-mark suffix for when I am implementing a method whose boolean return value is based on slightly more complex conditions than just the value of an attribute.
Cheers!
Edit, two years later, after a recent comment:
Ruby enforces certain naming conventions. Symbols in Ruby can't have question marks. Thus invocations of :my_boolean_attribute? both will fail with a NameError. Edit: not correct, just use the quoted syntax for a symbol, e.g., :"my_attribute?"
Symbols are immutable, attempting to assign to one will throw a SyntaxError.
The easiest way to quickly add a "question method" is to use aliasing for your reader method
class Foo
attr_accessor :dead
alias_method :dead?, :dead # will pick up the reader method
end
The attr_accessor symbol implies that the variable name is #my_boolean_attribute, so that's what you should be setting (not the symbol).
Also, you can't use ? for variables, just method names.
? is convention for methodnames, not variables. You can't use an instance variable named #foo?, however you could use a variable named #foo and name the (manually created) getter method foo? if you wanted to.
Monkey-patching metaprogramming - maybe it can be made more elegant, this is only a quick draft, and I haven't done metaprogramming for a little while...
# inject the convenience method into the definition of the Object class
class Object
def Object::bool_attr(attrname)
class_eval { define_method(attrname.to_s,
lambda { instance_variable_get('#' + attrname.to_s.chop) }) }
class_eval { define_method(attrname.to_s.chop+"=",
lambda { |x| instance_variable_set('#'+attrname.to_s.chop, x) }) }
end
end
### somewhere later
class MyClass
bool_attr :my_boolean_attribute?
def initialize
#my_boolean_attribute = true
end
end
# yet even more later
foo = MyClass.new
bar = MyClass.new
foo.my_boolean_attribute = 1
puts foo.my_boolean_attribute?
puts bar.my_boolean_attribute?
With this approach, you can be DRY and get the nice questionmark too. You just might need to pick a better name than "bool_attr", like, "bool_attr_accessor" or something similar.
The definitions that I made are a bit cranky, in a sense that the question mark is present in the original symbol. Probably a cleaner approach would be to avoid the questionmark in the symbol name and append it during the definition of the method - should be less confusing.
Oh, and almost forgot to include the obligatory link: Seeing metaclasses clearly
I looked through the answers, and while the accepted answer is on-target, it introduces "extra" noise in the class. The way I'd suggest solving this issue is:
class Animal
attr_writer :can_swim
def initialize(animal_type_name)
#can_swim = true
#animal_type_name = animal_type_name
end
def can_swim?
#can_swim
end
def to_s
#animal_type_name
end
end
dog = Animal.new('Dog in a bag')
dog.can_swim = false
puts "Can this #{dog} Swim? --- [#{dog_without_legs.can_swim? ? 'YEP!' : 'NOPE!'}]"