I'm currently working on a largish Ruby on Rails project. It's old enough and big enough that it's not clear if all views are actually in use.
Is there any script/plugin out there that can generate a list of unused view files?
Take a look at the following script on GitHub http://github.com/vinibaggio/discover-unused-partials
I wrote a script to find unused partials/views. I assumed, though, that "unused" means that a view-file is present for which no controller-method is defined (any more). The script does not check whether the view is called because there is no link from the default-route to it. This would have been far more complex.
Place the following script in the application's script folder:
#!/usr/bin/env ruby
require 'config/environment'
(Dir['app/controllers/*.rb'] - ['app/controllers/application.rb']).each do |c|
require c
base = File.basename(c, '.rb')
views = Hash.new
Dir["app/views/#{base.split('_')[0]}/*"].each do |v|
views.store(File.basename(v).split('.')[0], v)
end
unused_views = views.keys - Object.const_get(base.camelcase).public_instance_methods - ApplicationController.public_instance_methods
puts "Unused views for #{base.camelcase}:" if unused_views.size > 0
unused_views.each { |v| puts views[v] }
end
It is kinda hackish and unfinished, but it does the job - at least for me.
Execute it like this (you only need to change the execute-bit the first time with chmod):
chmod +x script/script_name
./script/script_name
Enjoy!
Just install and run the discover-unused-partials gem:
gem install discover-unused-partials
discover-unused-partials rails_root_directory
Iterate through your partials, grep (or awk) the project for the name of the file. Adjust your search regex to look for "render :partial" at beginning of line for generic partials (eg, "_form").
Related
I am using Ruby on Rails 3.2.2. I have implemented a Something plugin (it is almost a gem, but is not a gem) and all related files are in the lib/something directory. Since I would like to automate code generation related to that plugin, I came up with Ruby on Rails Generators. So, for the Something plugin, I am looking for implementing my own generators in the lib/something directory.
How should I make that and what are prescriptions? That is, for example, what rails generate command line should be invoked to properly generate all needed files in the lib/something directory? generators would still work with plugins (not gem)? what are advices about this matter?
I would make it a gem. I've made generators using gems, but I don't know if the generators would still work with plugins.
If you are having difficulty with the command line, I am guessing that you don't need any argument. (If you need an argument, I could copy the provided templates, and if I needed some other argument I'd be lost, so my advise is limited to non-argument.)
I have a generator gem which generates migration files needed for another gem. It checks if the migration with a given root name (w/o the timestamp prefix) is in db/migrate, and otherwise creates it.
Here is my code. I think this example is the help you need.
class ItrcClientFilesGenerator < Rails::Generators::Base
source_root(File.dirname(__FILE__) + "/../src")
desc "Generator to create migrations for needed db tables"
def create_itrc_client_files
prefix = DateTime.now.strftime("%Y%m%d%H%M")
existing_migrations =
Dir.glob("db/migrate/*itrc*").map do |path|
File.basename(path).gsub(/^\d*_/, '')
end
Dir.glob(File.dirname(__FILE__) + "/../src/*").sort.each_with_index do |src_filepath, index|
src_filename = File.basename(src_filepath)
unless existing_migrations.include?(src_filename.gsub(/^\d*_/, '')) then
this_prefix = "#{prefix}#{'%02i' % index}_"
dst_filename = src_filename.gsub(/^\d*_/, this_prefix)
copy_file(src_filename, "db/migrate/" + dst_filename)
end
end
end
end
I'm writing a command line command but want to TDD it. I'll be creating and deleting files and was wondering if there's a sandbox testing gem or something like that. I'm using ruby and rspec.
Depends on what you're trying to do, but I test most of my command line Ruby by mocking out the file system and STDIN/STDOUT. Using dependency injection I often end up with something along these lines:
describe Add do
it 'writes the result to standard out' do
console = mock('STDOUT')
console.should_receive(:puts).with('5')
Add.new(console).execute(3,2)
end
end
class Add
def initialize(out = STDOUT)
#out = out
end
def execute(command_line_args)
#out.puts(command_line_args.inject(:+))
end
end
Add.new.execute(ARGS)
By using default values I can inject in the test, but leave it out of the production code.
Hope that helps!
Brandon
The template generated by the newgem install_cucumber generator uses a pattern that I like quite a bit. Have a look at the support/env.rb and support/common.rb files it creates:
https://github.com/drnic/newgem/blob/master/rubygems_generators/install_cucumber/templates/features/support/env.rb.erb
https://github.com/drnic/newgem/blob/master/rubygems_generators/install_cucumber/templates/features/support/common.rb
Use of it in test looks like this:
in_tmp_folder do
# The current directory is now a generated tmp folder.
# If you stick to relative paths, everything you do in here should be safe
end
The files linked to above are for using this in cucumber tests, but it could easily be adapter to whatever framework you're using. The env.rb above deletes the tmp folder before each test starts.
You might also want to take a look at the sandbox gem.
gem install sandbox
Example usage is here: https://github.com/bdimcheff/sandbox
I am executing some system commands based on user actions such a mkdir,cd, cp -r skel/ dest/, and creating an apache vhost etc.
Where is the best place for this code to live? My instinct is to put them in the model as private methods, is this correct?
Thx
Jeff
Rails recommend having skinny controllers and fat models, but I believe that executing system commands is irrelevant to the model.
Since they depend of users actions, I'd suggest putting them in a library (/lib) and calling that lib from the controller.
Also, keep in mind that FileUtil might already do what you're looking for.
Instead of directly shelling out, I would advise using the FileUtils module, included with Ruby.
http://www.ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html
require 'fileutils'
FileUtils.mkdir 'test'
FileUtils.cd 'test'
FileUtils.cp_r 'skel', 'dest'
I would also put them in the model as private methods.
I am using Ruby on Rails 3.0.7 and I am writing some documentation for my application using RDoc. Since I have not found on the Web some good documentation with examples, what I would like to know is how to use the :include: directive at all.
Can you make me an example of using that in application files?
Here is the doc: http://rdoc.rubyforge.org/RDoc/Markup.html
And here is a very basic example:
First a ruby file, say /tests/my_func.rb
#:include: doc.txt
def my_function
puts "yo"
end
Then a doc /tests/documentations/doc.txt
This describes the method very well
In command line (executed from /tests):
rdoc -i /Users/benjaminroth/Sites/Tests/rdoc/descriptions
AIUI, :include: allows you to (surprise) include the contents of another file, keeping the same indentation level of the block in which the include appears.
It will look for the named file in the current directory, but it's something you can override by means of the --include switch.
If you want an example, this could prove useful.
I am facing an issue where my Rails application is set to cache classes when run in the staging or production environment. While load_paths only contains 'app/models', it appears that the initialization steps recursively caches everything in 'app/models'.
# Eager load application classes
def load_application_classes
if configuration.cache_classes
configuration.eager_load_paths.each do |load_path|
matcher = /\A#{Regexp.escape(load_path)}(.*)\.rb\Z/
Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
require_dependency file.sub(matcher, '\1')
end
end
end
end
The problem in this is that we have a sub directory within 'app/models' that contains files with require statements that reference a concurrent JRuby environment. Since Rails knows nothing of this environment our application breaks on load.
As it stands, here are the proposed solutions...unfortunately only #1 is ideal.
1) The simplest solution would be to exclude the culprit sub directory, but have not found anything how to accomplish this.
2) Monkey patch the load_application_classes method to skip the specific sub directory.
3) Move the sub directory out from under 'app/models'. Feels a bit hackish and would require quite a few code changes.
Thoughts?
As a temporary measure you could go with a version of option 2 and override the definition of load_application_classes, replacing it with an empty implementation. That would force you to explicitly require the classes you need but it would give you complete control over what gets loaded and would be a completely transparent solution.
It sounds like your application is sufficiently sophisticated that it's growing beyond the Rails framework. I know that this doesn't directly answer your question so appologies in advance but you may want to consider looking at an alternative Ruby framework like Merb. Rails is great but sooner or later you bump into edge of the framework - sounds like that's where you are now.
We made the switch to Merb last year and haven't regreated it.
Chris