Skip to content

Instantly share code, notes, and snippets.

@dyanagi
Last active September 22, 2019 18:04
Show Gist options
  • Save dyanagi/48f39fadb79134ba613d098a9cbdd18a to your computer and use it in GitHub Desktop.
Save dyanagi/48f39fadb79134ba613d098a9cbdd18a to your computer and use it in GitHub Desktop.
Ruby constants vs class methods
class Example
NAME = "this is constant"
SECRET_NAME = "this is a secret name"
private_constant :SECRET_NAME
def self.foo
@foo ||= "this is foo"
end
def self.bar
@@bar ||= "this is bar"
end
def self.baz
@foo
end
def self.qux
SECRET_NAME
end
def class_foo
@@foo
end
def instance_foo
@foo
end
def class_bar
@@bar
end
def instance_bar
@bar
end
end
puts Example::NAME.inspect # => "this is constant"
# puts Example::SECRET_NAME.inspect # => private constant Example::SECRET_NAME referenced (NameError)
puts Example.foo.inspect # => "this is foo"
puts Example.bar.inspect # => "this is bar"
puts Example.baz.inspect # => "this is foo"
puts Example.qux.inspect # => "this is a secret name"
example = Example.new
# puts example.class_foo.inspect # => uninitialized class variable @@foo in Example (NameError)
puts example.instance_foo.inspect # => nil
puts example.class_bar.inspect # => "this is bar"
puts example.instance_bar.inspect # => nil
# To conclude, it is possible to define a class method like this:
class SenderEmailAddress
DOMAIN_NAME = "yourcustomdomain.com"
private_constant :DOMAIN_NAME
def self.no_reply
@email_no_reply ||= "Example <no-reply@#{DOMAIN_NAME}>"
end
end
puts SenderEmailAddress.no_reply # => Example <no-reply@yourcustomdomain.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment