简体   繁体   中英

Filtering out rails reserved words?

As a Rails newbie, I keep running into one hard-to-debug issue: using a reserved Rails word (like :connection) for a model or column name...

Plus, sometimes I skip my first choice of a column name (like :date) because I'm not sure if it's allowed and I'd rather be safe.

Is there a gem, or a line I can add to customize the rails generator, that automatically checks for these and warns me?

I have found a four-year old list of these names, but more helpfully I can do modelA.methods & modelB.methods to get the list of reserved words. I'm not sure how comprehensive this is though - is it?

One trouble with a reserved words list for Rails is that different parts an application operate in different scopes. Some names that might be okay for a controller action are not okay as a model column, and visa-versa. Additionally, given that gems tend to mix all kinds of code into your application, a static reserved words list isn't going to be much use to you.

It would be great if generators checked for this, but they don't today, and it's probably tricky to implement, as the generators don't operate in exactly the same environment as the controllers/models themselves (ie mixing in all the same gems). Plus some people move on from generators after a while once they get the hang of the patterns, so it's good to have an answer for the non-generator world too.

I would suggest an alternate strategy. When you are questioning whether a particular method name or column name is a good idea, just ask that part of the application if it is already used, using respond_to? or instance_methods.include?

ActionController::Base.instance_methods.include? :display
=> true
# display is a bad action name

or use your actual controller:

MyController.new.respond_to? :display

For models:

ActiveRecord::Base.instance_methods.include? :status
=> false
# status is an okay column name

or

MyModel.new.respond_to? :status

Here is an alternative to help - http://reservedwords.herokuapp.com/ . This problem is tricky as @sampierson mentioned above - his methods should also work. Through trial and error you should cover most cases after enough conflicts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM