Skip to content

Instantly share code, notes, and snippets.

@ahoward ahoward/rails_root.rb
Last active Apr 20, 2018

Embed
What would you like to do?
# sometimes you need to calculate the rails_root from a subdirectory of a rails' app, eg, lib/capistrano/tasks/db.rake
# this code does it properly, but is verbose. golf it!
#
rails_root = File.expand_path(Dir.pwd)
until rails_root == '/'
if %w[ Gemfile app public ].all?{|entry| test(?e, "#{ rails_root }/#{ entry }")}
break
else
rails_root = File.dirname(rails_root)
end
rails_root = File.dirname(rails_root)
end
raise 'no rails_root!' if rails_root == '/'
@joelparkerhenderson

This comment has been minimized.

Copy link

commented Apr 20, 2018

Pathname.pwd.ascend do |x|; (x + "Gemfile").exist? and break x; end or raise "none"

@bradpauly

This comment has been minimized.

Copy link

commented Apr 20, 2018

I'd feel confident enough if it had Gemfile and app dir.

require "pathname"

rails_root = Pathname.pwd.ascend.select do |pn|
  File.file?(pn.join("Gemfile")) && File.directory?(pn.join("app"))
end

raise "Not found" if rails_root.nil?
@ahoward

This comment has been minimized.

Copy link
Owner Author

commented Apr 20, 2018

@joelparkerhenderson - oh! Pathname.ascend is teh sweet!

@ahoward

This comment has been minimized.

Copy link
Owner Author

commented Apr 20, 2018

@bradpauly - yes on both 'Gemfile' and 'app' !

@ahoward

This comment has been minimized.

Copy link
Owner Author

commented Apr 20, 2018

based on your awesome suggestions:

Pathname.pwd.ascend{|d| f = d.join('config/application.rb') and f.exist? && f.read.match('Rails') && (break(d))}

# or

Pathname.pwd.ascend{|d| (d.join('config/application.rb').read.match('Rails') && (break(d))) rescue nil}

# or

Pathname.pwd.ascend{|d| (d.join('Gemfile').read.match('rails') && (break(d))) rescue 42}
@bradpauly

This comment has been minimized.

Copy link

commented Apr 20, 2018

@ahoward Nice, I like reading config/application.rb.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.