Help resolving class and methods to reduce code
I have a method in the following folder:
/lib/app_name/my_file.rb /lib/app_name/other_file.rb
In my code, things look like this currently:
APP_NAME::OTHER_FILE.some_method?(APP_NAME::MY_FILE::A::B)
is there a way I can include this once in my code so I don't have to reference it like this?
Particularly I want to access the meth开发者_运维百科od 'some_method' and the enumerations in the class MY_FILE.
In ruby everything is an object, even classes.
So you can assign the classes (or modules) to variables in order to create a local shorthand, like this:
other = APP_NAME::OTHER_FILE
mine = APP_NAME::MY_FILE::A::B
other.some_method? mine
You already shouldn't need to pass the names of any classes/modules under which you are currently namespaced, so for example, you can drop the APP_NAME::
portion in those class names.
If you want to reduce the size of the class names even further, you either need to literally change your class names (assuming you named them badly) or do as Pablo says and just alias them to shorter names. And yes, you can 'require' them to get the aliases in a single line:
Create a file, for example, the way it's done in gems: lib/app_name.rb (in the case of a Gem, lib/gem_name.rb). Inside that:
require 'app_name/my_file'
require 'app_name/other_file'
And inside other_file.rb and my_file.rb, create your aliases:
class AppName::MyFile
...
end
AppName::MF = AppName::MyFile
So now you can just require 'app_name'
and all the classes will be loaded, along with their aliases.
Then you can reference AppName::MF
instead of AppName::MyFile
.
PS: You're using some weird naming convention, by the way ;) APP_NAME::MY_FILE as a class name is odd. Class names should be camel-cased.
精彩评论