Reputation: 4370
In ruby, it's pretty common to see variable named klass
that holds the name of the class name. Since class
is a reserved keyword, a misspelled word klass
serves the purpose.
I'm looking for a similar solution for class that I need to define for a file object.
Obviously
class File
end
won't work for me because it will start monkey patching the ruby's File
class which I don't intend.
Is there a name in practice that is commonly used for File
class? I stumbled upon the idea of using Fyle
but not sure if this is a great idea and wanted to check with the community :)
EDIT 1 Example of my usage.
In my rails app, I have a Product model which has many files. There are other models that also have file associations.
So I want to declare my associations like this
class Product
has_many :files, as: :file_attachable
end
class File # I cannot use `File` because it conflicts with ruby's `File`
belongs_to :file_attachable, polymorphic: true
end
Upvotes: 1
Views: 303
Reputation: 35443
Use a module namespace. This keeps your File class separate from Ruby's standard File class.
For example:
module Foo
class File
end
end
Usage:
f = Foo::File.new
For Rails ActiveRecord, you can do:
module Foo
class File < ActiveRecord::Base
end
end
Rails will automatically use the table name based on the class that inherits from Base, and not based on the module name:
Foo::File.table_name #=> "files"
You can provide your own table_name
if you prefer to customize:
module Foo
class File < ActiveRecord::Base
self.table_name = "foo_files"
end
end
Associations work the same way:
module Foo
class User
has_many :files # class is Foo::File
end
end
You can provide your own class_name
if you prefer to customize:
module Foo
class User
has_many :files, class_name: "Foo::File"
end
end
Upvotes: 2