Skip to content

Instantly share code, notes, and snippets.

@roktas
Forked from ecmelkytz/calendar_title.rb
Created November 22, 2018 10:23
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 roktas/d3340263c9e49f93a0b4ad10cd998970 to your computer and use it in GitHub Desktop.
Save roktas/d3340263c9e49f93a0b4ad10cd998970 to your computer and use it in GitHub Desktop.
Calender event concern
# 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
end
# 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
class_methods do
def registery
@registery ||= EventTitle.registery_from_yaml "#{Rails.root}/db/static_data/event_titles.yml"
end
def 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
def find_by_event_code(code)
find_by(name: registery[code].title)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment