Class alias in Ruby

后端 未结 5 1352
温柔的废话
温柔的废话 2020-12-08 13:45

I am developing a new Rails app based on a similar existing one. In my old app, I have Coupon class, which is very similar to Ticket in my new app. I want to reuse all code

5条回答
  •  感情败类
    2020-12-08 13:55

    Anyone coming here looking for how to alias a rails model class to have a new name:

    I was able to simply do Foo = Bar, but had to put Foo inside it's own model file so that I wouldn't get a Uninitialized Constant Error. e.g.

    # models/foo.rb
    Foo = Bar
    

    Also you may find weirdness trying to use the alias in associations like has_many, has_one etc. I've found you can usually get around those by using the root namespace (or appropriate namespace depending on how your models are structured) to make sure Rails is trying to autoload the right constant:

    has_many :foo, class_name: '::Foo'
    

提交回复
热议问题