Created
November 22, 2018 10:22
-
-
Save ecmelkytz/678c89d63627f7a938d2f999ce807d45 to your computer and use it in GitHub Desktop.
Calender event concern
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
# frozen_string_literal: true | |
class CalendarTitle < ApplicationRecord | |
# include EventTitle | |
# search | |
include PgSearch | |
pg_search_scope( | |
:search, | |
against: %i[name], | |
using: { tsearch: { prefix: true } } | |
) | |
# relations | |
has_many :calendar_title_types, foreign_key: :title_id, inverse_of: :title, dependent: :destroy | |
has_many :types, through: :calendar_title_types | |
has_many :calendar_events, dependent: :destroy | |
# validations | |
validates :name, presence: true, uniqueness: true | |
class << self | |
def registery | |
@registery ||= EventTitle.registery_from_yaml "#{Rails.root}/db/static_data/event_titles.yml" | |
end | |
def find_by_event_code(code) | |
find_by(name: registery[code].title) | |
end | |
end | |
end |
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
# frozen_string_literal: true | |
module EventTitle | |
extend ActiveSupport::Concern | |
Datum = Struct.new :name, :title, keyword_init: true | |
class Title | |
delegate :name, :title, to: :@datum | |
attr_reader :path, :code | |
def initialize(path, **datum) | |
@datum = Datum.new(**datum) | |
@path = path | |
@code = encode | |
end | |
private | |
PATH_SEPARATOR = '_' | |
def encode | |
[*path, name].map(&:to_s).join PATH_SEPARATOR | |
end | |
end | |
def self.registery_from_yaml(yaml_file) | |
registery = ActiveSupport::OrderedOptions.new | |
YAML.load_file(yaml_file).each do |category, data| | |
data.each do |datum| | |
type = Title.new([category], **datum.deep_symbolize_keys) | |
registery[type.code] = type | |
end | |
end | |
registery | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment