How to access the base namespace in Ruby?
::File
Prefixing with ::
accesses the 'root' of the namespace tree.
How do you find the namespace/module name programmatically in Ruby on Rails?
None of these solutions consider a constant with multiple parent modules. For instance:
A::B::C
As of Rails 3.2.x you can simply:
"A::B::C".deconstantize #=> "A::B"
As of Rails 3.1.x you can:
constant_name = "A::B::C"
constant_name.gsub( "::#{constant_name.demodulize}", '' )
This is because #demodulize is the opposite of #deconstantize:
"A::B::C".demodulize #=> "C"
If you really need to do this manually, try this:
constant_name = "A::B::C"
constant_name.split( '::' )[0,constant_name.split( '::' ).length-1]
Ruby, how to reference Root namespace?
What is the root object? If you mean main
object, you can't set constant at this level:
TOPLEVEL_BINDING.eval('self').const_set("MY_CONSTANT", "value")
# NoMethodError: undefined method `const_set' for main:Object
# from (irb):71
# from /home/malo/.rvm/rubies/ruby-2.1.0/bin/irb:11:in `<main>'
If you mean Object
object, do as follows:
Object.const_set("MY_CONSTANT", "value")
# => "value"
then you can use at the main
, or at any other level:
::MY_CONSTANT
# => "value"
Adding another confirmation
We can set a constant using Kernel
or using Object
and in both cases the constant will be accessible from the root namespace:
Kernel.const_set("KERNEL_CONSTANT", "value")
Object.const_set("OBJECT_CONSTANT", "value")
puts !!(defined? ::KERNEL_CONSTANT) # => true
puts !!(defined? ::OBJECT_CONSTANT) # => true
But if we set a constant in the root namespace this constant is actually set in Object
and not in Kernel
:
::ROOT_CONSTANT = "value"
puts !!(defined? Object::ROOT_CONSTANT) # => true
puts !!(defined? Kernel::ROOT_CONSTANT) # => false
Accessing a class's containing namespace from within a module
In your example, User
is just a constant that points to a Class
object. You can easily create another constant pointer when MyMagicMixin
is included:
module MyMagicMixin
class <<self
def self.included(klass)
base.extend MyMagicMixin::ClassMethods
create_pluralized_alias(klass)
end
private
def create_pluralized_alias(klass)
fq_name = klass.to_s
class_name = fq_name.demodulize
including_module = fq_name.sub(Regexp.new("::#{class_name}$", ''))
including_module = including_module.blank? ? Object : including_module.constantize
including_module.const_set class_name.pluralize, klass
end
end
module ClassMethods
# cass methods here
end
end
Of course this doesn't answer whether you should do such a thing.
How to access a namespace method in Ruby console?
If you want to call a method defined inside a .rake
file you do something similar to what @Nate said, but instead of calling the raketask, call the method:
require 'rake'
Rake.load_rakefile 'lib/tasks/namespace_name.rake'
method_name(arg1, arg2)
It feels kind of strange that you don't need to specify the namespaces but I just tried this and it worked.
How to access top-level namespace via metaprogramming in Ruby?
Michael Gorman's suggestion of String Interpolation was good, this is what ended up working:
klass = "::#{model_name.to_s.capitalize}".constantize
How to get all class names in a namespace in Ruby?
Foo.constants
returns all constants in Foo
. This includes, but is not limited to, classnames. If you want only class names, you can use
Foo.constants.select {|c| Foo.const_get(c).is_a? Class}
If you want class and module names, you can use is_a? Module
instead of is_a? Class
.
Ruby using namespace/module
If you want to shorten these, you can just import that namespace:
Net::HTTP.start(...)
include Net
# HTTP.start(...)
Be careful when you import aggressively as it might cause conflict within your class if you get carried away.
An alternative is to create aliases:
HTTP = Net::HTTP
Get = Net::HTTP::Get
The "correct" way is to just spell it out and not get too flustered by that. A typical Ruby program will bury this sort of low-level behavior beneath an abstraction layer so it's rarely a big deal.
Related Topics
Safe Navigation Equivalent to Rails Try for Hashes
Deleting the Current Session with Rack::Session::Cookie
Ruby - How to Write a New File with Output from Script
Error: While Executing Gem ... (Typeerror) Incompatible Marshal File Format (Can't Be Read)
Rails First_Or_Create Activerecord Method
Use Separate Authentication Model with Devise on Rails
Begin Rescue Not Catching Error
Is It a Bad Idea to Reload Routes Dynamically in Rails
Paperclip: Upload from Url with Extension
In Ruby What Is the Meaning of Colon After Identifier in a Hash
Bundle Command Not Found Windows X64
Trouble on Rendering a Template Passing a Local Variable
Convert HTML to Plain Text (With Inclusion of <Br>S)
Equivalent of Iconv.Conv("Utf-8//Ignore",...) in Ruby 1.9.X
Reinstall Every Gem for Each Ruby Version
How to Test Instance Variable Was Instantiated in Controller with Rspec