My model name in one of rails app is OrganizationUser
and is there any way to create alias name for this model as OU or OrgUser so that I can use in rails console..
Asked
Active
Viewed 9,634 times
5

shajin
- 3,214
- 5
- 38
- 53
-
2http://stackoverflow.com/questions/7795809/class-alias-in-ruby – Sergey Kishenin Jun 22 '12 at 10:49
2 Answers
11
If kishie's answer does not suit you you could create another model that inherits from OrganizationUser:
class OU < OrganizationUser
end
or
class OrgUser < OrganizationUser
end

pepe
- 555
- 4
- 8
-
This is actually a little risky under a few circumstances, particularly with STI models, or for anything that expects specific class types. It'll work, but makes me a little nervous. – Dave Newton Jun 23 '12 at 03:43
-
@DaveNewton: To tell the truth I totally missed that the op's goal was to use the names in the console, in which case I would have gone for kishie's answer (OU = OrganizationUser), I've used that in the past myself. However I don't see a problem with the above code if what you are looking after is just using a different name for a given class. – pepe Jun 23 '12 at 13:39
-
2Under STI it would create the wrong type column in the DB; this *may* not be a problem, but it introduces a type hierarchy that doesn't really exist. Not *necessarily* an issue, like I said, but IMO not a great idea--YMMV :) – Dave Newton Jun 23 '12 at 13:49
-
OU = OrganizationUser works well, but where can I put that so that it automatically runs every time I run rails c? – Roman Gaufman Jun 24 '22 at 13:07
-
@RomanGaufman Playing with Rails 7 I created `renamers/u.rb` inside of the `app` folder with just one line: `U = User`. You should be able to do something similar to that for your class. – pepe Jun 26 '22 at 01:09
1
To work on a more cleaner side . Suppose you have a model
class Home < ActiveRecord::Base
class << self
def agent
p "This is a Dummy String"
end
end
end
Step 1
Create a alias.rb inside your lib. Which will contain your Alias mappings and Constants holding those mapping
module Alias
C = Home #to make a alias of class
H = Home.new #a class object alias
end
Step 2
Goto rails c
rails c
"inside it for loading"
Loading development environment (Rails 3.2.1)
ruby-1.9.3-preview1 :001 > require 'alias'
=> true
ruby-1.9.3-preview1 :002 > include Alias
=> Object
ruby-1.9.3-preview1 :003 > C
=> Home(id: integer, created_at: datetime, updated_at: datetime)
ruby-1.9.3-preview1 :004 > H
=> #<Home id: nil, created_at: nil, updated_at: nil>

AnkitG
- 6,438
- 7
- 44
- 72