Rails Reserved Class Names

Rails Reserved Class Names

This page has a very long list of words not to use:

https://reservedwords.herokuapp.com/words

Because 'class' comes up very commonly as a name with metaprogamming, I think the accepted ruby alternative is 'klass'. This is obviously a different context from your graduating class situation, but maybe still helpful.

Reserved names with ActiveRecord models

Reserved Word List

ADDITIONAL_LOAD_PATHS
ARGF
ARGV
ActionController
ActionView
ActiveRecord
ArgumentError
Array
BasicSocket
Benchmark
Bignum
Binding
CGI
CGIMethods
CROSS_COMPILING
Class
ClassInheritableAttributes
Comparable
ConditionVariable
Config
Continuation
DRb
DRbIdConv
DRbObject
DRbUndumped
Data
Date
DateTime
Delegater
Delegator
Digest
Dir
ENV
EOFError
ERB
Enumerable
Errno
Exception
FALSE
FalseClass
Fcntl
File
FileList
FileTask
FileTest
FileUtils
Fixnum
Float
FloatDomainError
GC
Gem
GetoptLong
Hash
IO
IOError
IPSocket
IPsocket
IndexError
Inflector
Integer
Interrupt
Kernel
LN_SUPPORTED
LoadError
LocalJumpError
Logger
Marshal
MatchData
MatchingData
Math
Method
Module
Mutex
Mysql
MysqlError
MysqlField
MysqlRes
NIL
NameError
NilClass
NoMemoryError
NoMethodError
NoWrite
NotImplementedError
Numeric
OPT_TABLE
Object
ObjectSpace
Observable
Observer
PGError
PGconn
PGlarge
PGresult
PLATFORM
PStore
ParseDate
Precision
Proc
Process
Queue
RAKEVERSION
RELEASE_DATE
RUBY
RUBY_PLATFORM
RUBY_RELEASE_DATE
RUBY_VERSION
Rack
Rake
RakeApp
RakeFileUtils
Range
RangeError
Rational
Regexp
RegexpError
Request
RuntimeError
STDERR
STDIN
STDOUT
ScanError
ScriptError
SecurityError
Signal
SignalException
SimpleDelegater
SimpleDelegator
Singleton
SizedQueue
Socket
SocketError
StandardError
String
StringScanner
Struct
Symbol
SyntaxError
SystemCallError
SystemExit
SystemStackError
TCPServer
TCPSocket
TCPserver
TCPsocket
TOPLEVEL_BINDING
TRUE
Task
Text
Thread
ThreadError
ThreadGroup
Time
Transaction
TrueClass
TypeError
UDPSocket
UDPsocket
UNIXServer
UNIXSocket
UNIXserver
UNIXsocket
UnboundMethod
Url
VERSION
Verbose
YAML
ZeroDivisionError
@base_path
accept
Acces
Axi
action
attributes
application2
callback
category
connection
database
dispatcher
display1
drive
errors
format
host
key
layout
load
link
new
notify
open
public
quote
render
request
records
responses
save
scope
send
session
system
template
test
timeout
to_s
type
URI
visits
Observer

Database Field Names

created_at
created_on
updated_at
updated_on
deleted_at
(paranoia
gem)
lock_version
type
id
#{table_name}_count
position
parent_id
lft
rgt
quote_value

Ruby Reserved Words

alias
and
BEGIN
begin
break
case
class
def
defined?
do
else
elsif
END
end
ensure
false
for
if
module
next
nil
not
or
redo
rescue
retry
return
self
super
then
true
undef
unless
until
when
while
yield
_ FILE _
_ LINE _

Models with reserved keywords

This problem is addressed with modules:

Modules are a way of grouping together methods, classes, and
constants. Modules give you two major benefits:

  1. Modules provide a namespace and prevent name clashes.
  2. Modules implement the mixin facility.

[...]

Modules define a namespace, a sandbox in which your methods and
constants can play without having to worry about being stepped on by
other methods and constants.

In your case:

module MyRailsApp
class File
...
end
end

whereby your File class is used as MyRailsApp::File. This is the typical solution in Ruby, in Ruby on Rails this might be handled differently, please see the following references for an in depth discussion:

  • Handling namespace models (classes) in namespace
  • ActiveRecord: Can haz namespaces?
  • Namespaced models and controllers
  • Namespaced models
  • A simple alternative to namespaced models

Ruby reserved class method names

You can always see a list of the methods implemented by default for every class:

class Try
end

t = Try.new
puts t.methods.sort

EDIT: actually you may also want to look at the private methods (where initialize is):

puts t.private_methods.sort

Subject a reserved word in Rails?

As you correctly say, SubjectsHelper is already provided by Social Stream. See:

https://github.com/ging/social_stream/blob/master/base/app/helpers/subjects_helper.rb

Your solution is working because you are reopening the module, which is a valid action in Ruby.

Classes with reserved names (keywords). How do you deal with this?

First off, this depends a lot of the language.

TALK TO YOUR TEAM

Secondly, and most important! Conventions may change a lot depending on your team. Talk to your team, and agree on one convention to use. Never forget this.

Conventions

There are universal conventions/standards to follow, and like you mentioned, using keywords is usually a bad-ish idea. I for one try to avoid them, just as I avoid using digits in my variable-names, even if the specific language I'm working with allows it. Reason? It's easier to stick with "let's avoid problems by mixing rules between languages" than having to check the rules each time.

I often spend 30 minutes thinking of the perfect variable name, so I am quite used to this kind of pondering.

Length

Excessively long variable names is bad, because it hinders flow reading, while excessively short variable names are also bad because it is hard to guess what word you want. You could call it srvc, sure, but who will know what that means in a month (unless you comment it, sure). Dropping the vowels in user-variables is quite common, actually, especially in low-level/old languages.

Specific case

As for this specific example, I wouldn't think of MedicalService as a keyword. First off, it's part of a longer name, like MedicalFile doesn't look like a file from the system at all, but rather a form with medical data on it.

I don't exactly know what this MedicalService does, but it seems like a generic (abstract, probably) class name for services that you can ask for at the counter of a hospital, so I'm assuming that.

GenericMedicalThingToDo is a funny way to avoid the keyword, but I wouldn't call it that. MedicalUseCase seems quite better, and gets to the point.

On the other hand, if this is just a string stating the use case for whatever it is the user has chosen (considering you mentioned Angular), I would just stick with userMedicalChoice (drop the PascalCase to camelCase).

If you need to use a word that is actually a keyword, which often happens, you might want to add a _ on the end or the beginning of it. This is not usually good for interfaces, as it's conventional to only use those internally/privately. Some conventions use double _ for private, and single _ to avoid dupes.

Last point:

Having keywords as part of a longer variable name is not a problem in any of the many programming languages I have sailed in, so just call it MedicalService, or GenericMedicalService if you're going to subclass it.

PS: Read up on some conventions of different languages, like PEP-8, and PEP-256 from Python, or Google's C++ conventions. While not specifically being valid for all languages, they do give you something pin-pointers to what is important.

creating a model with name import is it reserved word in rails 3?

Solved it was incorrect naming of controller import model that caused this, I missed the S char in the filename

Is it possible to have a keyword argument named `class` or other reserved name in Ruby?

Kind of. You have to avoid confusing the Ruby lexer by avoiding the literal keyword in your code, though. In Ruby 2.2+, you can get around it with binding.local_variable_get:

def link_tag(url, class: nil)
format('<a href="%s" class="%s"></a>', url, binding.local_variable_get(:class))
end

link_tag("http://stackoverflow.com", class: "fancy")
# => "<a href=\"http://stackoverflow.com\" class=\"fancy\"></a>"

This isn't really a very clean way of doing things, though, and is likely to be confusing. I would just try to rename my arguments to not conflict with the language if I were to use keyword args, though (ie, css_class or the conventional klass, etc).



Related Topics



Leave a reply



Submit