简体   繁体   中英

How to separate custom code from generated in RoR

I've been developping a bit in .net and I'm discovering rails these days. I'm familiar with code generation and something has seemed quite usefull in .net. It's that when we do custom code, like a new method in a Model, we do it in a separate file (with a public partial class ) from the code that has been automatically generated. So if we change the type of an attribute and regenerate the code, the methods we have created are not erased.

I've not found something similar in the RoR tutorials on the internet. Does it work the same or is there another solution to easily rescaffold code without erasing custom methods?

Thanks

If you only need to generate ORM related code in C#, you don't need to worry code generation problem in Rails. Thanks to the dynamic typing & meta-programming ability of Ruby and the "Convention over Configuration" philosophy in Rails, you don't need to generate ORM code with tools at all.

class Product < ActiveRecord::Base
end

The above class will automatically get mapped to products table in the database. You can access the value of each column via accessor like p.name . You can retrieve products via Product.find , Product.where , etc.

These codes are injected via subclassing or mixins (as Amir pointed out), or more generally, generated at runtime on demand with the help of BasicObject#method_missing .

You can take a look at Active Record Basics , and it may be helpful to go through the entire guide to experience the Rails agile development.

In ruby you can do that with a mixin - create a Module and then include it in your class.

There's a lot of information about it online, check out this post here

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