Skip to content

Instantly share code, notes, and snippets.

@emmanuellyautomated
Last active May 9, 2016 14:42
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 emmanuellyautomated/c6c20c049d87fe7814cab71b0832c29a to your computer and use it in GitHub Desktop.
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
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
@emmanuellyautomated
Copy link
Author

Put this file wherever and import into your console. Instantiate with your desired Rails (absolute) app path and you're off to the races!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment