How to create own generator in rails 4 - ruby-on-rails

I want to create own customized generator for scafflod so that i can change the default layout of generated .html.erb or .html.haml for a particular application.
I want to customize the layouts

Making generators is a good idea when you want a specific layout applied to few of your resources. It might be like you have an normal user section and admin user section with different layouts.
You may have a good reference of making a generator from here:http://railscasts.com/episodes/218-making-generators-in-rails-3?view=asciicast

There is some pretty nice stuff you can do with this. Problem is it is very badly documented, but once you know where to store the various template files, you're on the move:
It all starts in lib/templates
lib/templates/active_record/model/model.rb contains the model template
lib/templates/factory_girl/model/fixtures.erb contains the factory girl template
lib/templates/rails/scaffold_controller/controller.rb the controller
lib/templates/rspec/model/model_spec.rb the rspec model
lib/templates/rspec/scaffold/controller_spec.rb the rspec controller
lib/templates/haml/scaffold/_form.html.haml the views (idem dito for edit, index, new and show)
If you need more info on the templates, just let me know!

Related

Creating Methods to an existing Controller via Terminal

I have an existing model that I'd like to add a number of methods to. While I could manually add the methods to the controller as well as its corresponding style/script templates and routes I'd much rather have them done just as I would've when I created the controller in the first place:
rails generate ControllerName hello goodbye
Is there any way to accomplish this?
I think this is a perfectly valid thing to want to do. However the general concensus seems to be that it is too trivial hence why there is no option for it.
A couple of things you could do though:
If you are only adding one or two actions to an otherwise complex controller you could generate another dummy controller with just those two actions. Then copy over the new bits to your existing controller and trash the dummy one. Something like git is great for keeping a track on what the generator changed here.
Alternatively if you want to add a lot of new actions to a trivial controller you could save off the original files, let the generator overwrite the existing controller and then put back the original bits.
Remember you can always use the --pretend option on the generator to see what it would create without actually doing it. This can be useful especially to see what view files it would create for the actions in your case.
You can do
rails generate controller mycontroller hello goodbye
This would generate controller called mycontroller with methods hello and goodbye.

Where to store editable content?

I am building a Rails app that is intended to be eventually used by non-technical people. It consists of a few pages with blocks of text and a special page with interactive canvas drawings.
I want to allow them to easily edit any piece of text contained in the application. What are the best ways to achieve that? Currently, text is written in the different views of the application, which does not allow them to edit it without having to connect via FTP or similar and search for the right file.
I am thinking of three solutions:
Store all blocks of text in the database. On each page, fetch the requires blocks and insert them before rendering. Build a page that lists all blocks in the database in editable areas with a save button.
Store all blocks of text in a json file. Create a model that can read the file and fetch the blocks required by the views. Build a page that lets you edit each block and save it in the file.
Create some kind of password-protected admin interface that fetches all file in the views directory, use regexp to find blocks of text and allow the users to edit each block and save.
From my point of view, all of my three solutions look pretty bad. It does not feel okay to do so many calls to the database? Store your entire website text in a file? Parse HTML with regexps?
What are the usual approaches used to solve this problem?
There's a great book out there: Crafting Rails 4 Applications. Here's the link to source code from the book. You will find example in templater folder. Basically, you will be able to create custom templates based on the request parameters (just like Rails does).
Update. Here's a couple of links:
Default views in Rails 3.0 with custom resolvers by José Valim (author of the book, by the way).
Implementing a Rails 3 View Resolver.
Also, here's 5 coins from me. Basically, it works like this. You need to define your own resolver and connect it to your ApplicationController (or any other controller you want):
class Resolver < ActionView::Resolver
# some code here
end
class ApplicationController < ActionController::Base
append_view_path Resolver.new
end
During the rendering process, Rails will ask your controller's resolvers to provide a template (it will go through each of them, until it finds template or until there won't be any resolvers left). In order to provide template, your resolver needs a find_templates method:
def def find_templates(name, prefix, partial, details)
# some processing here
end
So, based on this method parameters, you're going to provide some database records. But even if you have some kind of model already, Rails expects this method to return ActionView::Template instance. It can be initialized like this:
ActionView::Template.new(source, identifier, handler, details)
So, that's how your find_templates should look like:
def find_templates(name, prefix, partial, details)
template = DatabaseTemplate.find... # your custom model for DB templates
ActionView::Template.new... # initializing actual template
end
Both model and resolver in detail are presented in the book's source code (templater/3_final/app/models/sql_template.rb).
I have done that a couple times with awesome user satisfaction by using this:
http://jejacks0n.github.io/mercury/
There is also a Railscast available which gives you a good overview and step by step instructions:
http://railscasts.com/episodes/296-mercury-editor
Hope it helps. It looks good and is easy to use for end users.

Create a new action for existing controller

I know this is probably a newbie question, but is it possible to create a new action (method in controller & associated view) from the command line on an existing controller?
For example, I already have a controller named 'Products'. Could I run:
rails g controller products [new_action]
and then rails would insert:
def [new_action]
end
Into my products controller and create a new file called '[new_action].html.erb' in the views/products/ directory? I have already googled this, but no satisfactory answer was returned. Also, I would just go ahead and try it, but I am pretty far into the development of my current app and really do not want to mess anything up.
I'm pretty sure you won't be able to do this in a 100% automated way. The reason is that Rails doesn't know what you've done with your routes or controller, and it would require some logic to know how to update these existing files. Your best bet is to just add the new action manually. Add the new method to your controller, update your routes file, and add the view. It will probably take 1 minute at most. Also, if you're not using version controller (which your question eluded to), then you don't have to worry about it automatically overwriting something.
we can create manually the action in the controller and view but you should also add test statements that because should be good automated process, something like rails generate controller NAME [action action] option m
m = merge
Rails provide posibility of creating custom generators (but this is more advanced subject), which can be tailored for your needs.
More info:
http://guides.rubyonrails.org/generators.html

creating a simple html page in ruby

Following the ruby tutorial I am trying to create a simple html page.
I will need a controller, i think for some presentation manipoulation but not DB.
I thought that I would create a model, controller and view but then I see that
rails generate model mainMenu freeData1:string freeData2:string
creates the db script.
In order to achieve a simple managed html page that would not require db, what should I create ?
controler only? what is the best practice?
what methods should I put in it for it to be displayed?
thanks.
Yes, you'll just want a controller for the pages which will also create a views folder for your new controller that you can put HTML/ERB/whatever files in.
Since youre not working with the db, you can probably skip the need of a model.

Scaffold default files are the best practice?

Hey, i have some experience with MVC. but I'm new to rails. I'm using the scaffold command to generate some default files. The model looks clean and nice, but the controller and the views aren't really dry. The contents of new.html.erb and edit.html.erb are almost the same and the methods new/edit and create/update are doing almost the same thing. In other frameworks i've used only one view for updating and creating new entries and also the same method in my controller by setting the id as an optional parameter. Do they use this structure to keep things RESTful (i have not much of a clue about rest :()? Is it the best practice to use this default stuff for crud?
The scaffold generator is a pretty good place to start. As you pointed out, there are some things which are not that great about it. I think most people take what the scaffold generates and then fix it up to their liking. For example, you can extract the form part from new.html.erb and edit.html.erb and place it in a partial _form.html.erb. Then update new.html.erb and edit.html.erb to include that partial to render the form. I think that for Rails 3, the scaffold generator has been changed to do this by default.
It does seem like new and edit, and create and update are pretty much the same, but you need to remember that they are mapped to different HTTP methods and URLs, which ties in to the whole RESTful resource idea. Check out the RailsGuides for routing, the section CRUD, Verbs, and Actions has a nice table of the seven different routes and the differences between them.
You should check out ryanb's nifty-generators:
http://github.com/ryanb/nifty-generators
The scaffolding creates a partial view called _form that then gets referenced from the new and edit views. It also comes with a bunch of other nice options -- like generating your views in haml or your tests in Shoulda or RSpec.
If they wanted you to keep it they wouldn't call it "scaffolding." It's just there to make everything work out of the box. If you put it into production you will more than likely be laughed at.

Resources