Last active
May 9, 2016 14:42
-
-
Save emmanuellyautomated/c6c20c049d87fe7814cab71b0832c29a to your computer and use it in GitHub Desktop.
Ruby object that returns all declared associations in your Rails models when given the filepath to your Rails app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Associator | |
attr_reader :rails_app_dir, :associations | |
ASSOCIATION_TYPES = [ | |
"belongs_to", | |
"has_one", | |
"has_many", | |
"has_and_belongs_to_many" | |
] | |
def initialize(rails_app_dir) | |
@rails_app_dir = rails_app_dir | |
@associations = fetch_associations | |
end | |
def renew | |
return Associator.new(@rails_app_dir) | |
end | |
private ########################################### | |
def fetch_models_list | |
return Dir.open(@rails_app_dir.gsub(/\/$/, "") + "/app/models").entries.select {|entry| entry.match(/.rb$/)} | |
end | |
def fetch_associations | |
payload = {} | |
models_list = fetch_models_list | |
unless models_list.empty? | |
models_list.each do |filename| | |
filepath = @rails_app_dir + "/app/models/" + filename | |
payload[filename.gsub(/.rb$/, '')] = File.readlines(filepath).select {|line| line =~ Regexp.new(ASSOCIATION_TYPES.join("#{/\b/}|"))} | |
end | |
payload.each {|filename, associations| | |
associations.map! {|association| association.strip} | |
payload[filename] = associations.group_by {|e| e.match(Regexp.new ASSOCIATION_TYPES.join("#{/\b/}|"))[0]} | |
} | |
pp payload | |
return payload | |
else | |
return false | |
end | |
end | |
################################################### | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Put this file wherever and import into your console. Instantiate with your desired Rails (absolute) app path and you're off to the races!