Files
sx-fc/app/models/menu.rb
2018-03-19 18:13:38 +06:30

86 lines
2.5 KiB
Ruby
Executable File

class Menu < ApplicationRecord
require 'spreadsheet'
has_many :menu_categories, dependent: :destroy
validates_presence_of :name, :valid_days, :valid_time_from, :valid_time_to
# validates_format_of :valid_days, :with => /\A([0-7]{1}(,[0-7]{1})*)?\Z/i
#Default Scope to pull the active version only
default_scope { where(is_active: true).order("created_at asc") }
def self.current_menu
today = DateTime.now
day_of_week = today.wday
menus = Menu.where("is_active = true and '#{today.strftime("%H:%M")}' between TIME(valid_time_from) and TIME(valid_time_to)")
current_menu = nil
#Loop through the menu which is valid days - get the first menu out and return result
menus.each do |menu|
if menu.valid_days.include?(day_of_week.to_s)
current_menu = menu
break
end
end
return current_menu
end
def self.destroyMenu(menu)
cats = MenuCategory.where("menu_id=?",menu.id)
cats.each do |cat|
abc = MenuCategory.destroyCategory(cat)
end
menu.destroy
return false
end
def self.to_csv
m_attributes = %w{name is_active valid_days valid_time_from valid_time_to created_by created_at updated_at}
CSV.generate(headers: true, row_sep: "\r\n") do |csv|
csv << m_attributes
menu = Menu.all
menu.each do |user|
csv << m_attributes.map{ |attr| user.send(attr)}
end
end
end
def self.import(file)
spreadsheet = Roo::Spreadsheet.open(file.path)
puts spreadsheet.info
spreadsheet = Roo::Excelx.new(file.path)
puts spreadsheet.info
# Use the extension option if the extension is ambiguous.
spreadsheet = Roo::Spreadsheet.open(file.path, extension: :xlsx)
puts spreadsheet.info
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header,spreadsheet.row(i)].transpose]
menu = Menu.new
menu.name = row["name"]
menu.is_active = row["is_active"]
menu.valid_days = row["valid_days"]
menu.valid_time_from = row["valid_time_from"]
menu.valid_time_to = row["valid_time_to"]
menu.created_by = row["created_by"]
menu.save
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".csv" then Roo::CSV.new(file.path,nil,:ignore)
when ".xls" then Roo::Excel.new(file.path,nil,:ignore)
when ".xlsx" then Roo::Excelx.new(file.path,nil,:ignore)
else raise "Unknown File type: #{original_filename}"
end
end
end