|
1 | 1 | module SeedsHelper |
2 | | - def update_from_seeds(type, unique_key, value_attribute) |
3 | | - data = YAML.load_file(Rails.root.join("db/seeds/#{type}.yml")) |
4 | | - cls = type.to_s.singularize.classify.constantize |
5 | | - data.each do |seed| |
6 | | - cls.unscoped.where(unique_key => seed[unique_key.to_s]).update(value_attribute => seed[value_attribute.to_s]) |
| 2 | + # Gets the list of seed file paths |
| 3 | + # @param seed_name [String, nil] optional specific seed name to run |
| 4 | + # @return [Array<String>] |
| 5 | + def self.files(seed_name) |
| 6 | + find_glob = if seed_name.present? |
| 7 | + "db/seeds/**/#{seed_name.underscore}.yml" |
| 8 | + else |
| 9 | + 'db/seeds/**/*.yml' |
| 10 | + end |
| 11 | + |
| 12 | + # Get all seed files and determine their model types |
| 13 | + Dir.glob(Rails.root.join(find_glob)) |
| 14 | + end |
| 15 | + |
| 16 | + # Parses model classes from the list of file paths |
| 17 | + # @param files [Array<String>] list of seed file paths |
| 18 | + # @return [Array<Class>] |
| 19 | + def self.types(files) |
| 20 | + files.map do |f| |
| 21 | + basename = Pathname.new(f).relative_path_from(Pathname.new(Rails.root.join('db/seeds'))).to_s |
| 22 | + basename.gsub('.yml', '').singularize.classify.constantize |
7 | 23 | end |
8 | 24 | end |
| 25 | + |
| 26 | + # Prioritizes models such that dependent ones are created after the specified ones |
| 27 | + # @param types [Array<Class>] list of model classes |
| 28 | + # @param files [Array<String>] list of seed file paths |
| 29 | + # @return [Hash<String, Class>] |
| 30 | + def self.prioritize(types, files) |
| 31 | + priority = [PostType, CloseReason, License, TagSet, PostHistoryType, User, Ability, CommunityUser, Filter] |
| 32 | + |
| 33 | + files.zip(types).to_h.sort do |a, b| |
| 34 | + (priority.index(a.second) || 999) <=> (priority.index(b.second) || 999) |
| 35 | + end.to_h |
| 36 | + end |
9 | 37 | end |
0 commit comments