Skip to content

Instantly share code, notes, and snippets.

@ahoward
Last active April 20, 2018 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahoward/284bbce45fc5efaf0ceed424eb63aa2e to your computer and use it in GitHub Desktop.
Save ahoward/284bbce45fc5efaf0ceed424eb63aa2e to your computer and use it in GitHub Desktop.
# 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 == '/'
@ahoward
Copy link
Author

ahoward commented Apr 20, 2018

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

@ahoward
Copy link
Author

ahoward commented Apr 20, 2018

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

@ahoward
Copy link
Author

ahoward 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
Copy link

@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