text stringlengths 10 2.61M |
|---|
class ReviewsController < ApplicationController
skip_before_action :require_login
def create
@review = Review.new(review_params)
if @review.save
flash[:status] = :success
flash[:result_text] = "Successfully created your review!"
redirect_to product_path(@review.product_id)
else
flash[:status] = :failure
flash[:result_text] = "Could not create your review."
flash[:messages] = @review.errors.messages
redirect_back(fallback_location: root_path)
end
end
private
def review_params
params.require(:review).permit(:name, :description, :product_id, :rating)
end
end
|
class CreateElectronicPortals < ActiveRecord::Migration
def change
create_table :electronic_portals do |t|
t.references :organ, index: true, foreign_key: true
t.string :value
t.timestamps null: false
end
end
end
|
#
# Cookbook Name:: nullmailer
# Recipe:: default
#
# Copyright 2010, Estately, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# remove postfix, we don't want both
package("postfix") { action :purge }
package "nullmailer"
service "nullmailer" do
supports [ :start, :stop, :restart, :reload ]
action :enable
end
file "/etc/mailname" do
owner "root"
group "root"
mode 0644
content "#{node.nullmailer.mailname}\n"
notifies :restart, resources(:service => "nullmailer")
end
file "/etc/nullmailer/remotes" do
owner "root"
group "root"
mode 0644
# dup, lest we mutate the actual attribute value
remote = node.nullmailer.relayhost.dup
remote << " smtp"
if node.nullmailer.username
remote << " --user=#{node.nullmailer.username}"
end
if node.nullmailer.password
remote << " --pass=#{node.nullmailer.password}"
end
content "#{remote}\n"
notifies :restart, resources(:service => "nullmailer")
end
|
# frozen-string_literal: true
module Decidim
module Opinions
class CollaborativeDraftWithdrawnEvent < Decidim::Events::SimpleEvent
i18n_attributes :author_nickname, :author_name, :author_path
delegate :nickname, :name, to: :author, prefix: true
def nickname
author_nickname
end
def author_path
author.profile_path
end
private
def author
@author ||= Decidim::UserPresenter.new(author_user)
end
def author_user
@author_user ||= Decidim::User.find_by(id: extra[:author_id])
end
end
end
end
|
load File.expand_path("../tasks/svn.rake", __FILE__)
require 'capistrano/scm'
class Capistrano::Svn < Capistrano::SCM
# execute svn in context with arguments
def svn(*args)
args.unshift(:svn)
context.execute *args
end
module DefaultStrategy
def test
test! " [ -d #{repo_path}/.svn ] "
end
def check
test! :svn, command_with_credentials(:info), repo_url
end
def clone
svn command_with_credentials(:checkout), repo_url, repo_path
end
def update
svn command_with_credentials(:update)
end
def release
svn :export, '--force', '.', release_path
end
def fetch_revision
context.capture(:svnversion, repo_path)
end
private
def command_with_credentials(cmd)
"#{cmd} --username #{fetch(:scm_username)} --password #{fetch(:scm_password)}"
end
end
end
|
# A temporary content format used as a splash page for scheduled documents.
#
# When a new document is scheduled for publication, a "coming_soon" content item
# is pushed to the Publishing API, along with a `PublishIntent` for the
# scheduled publication time. This is to get around the fact that the current
# caching infrastructure will cache a 404 for 30 minutes without honouring any
# upstream caching headers it receives. By publishing a temporary "coming soon"
# page, we can get around this issue and ensure that the cache headers that are
# set according to the scheduled publication time will be honored, thus
# preventing a 404 page from being cached for up to 30 minutes from the point
# the document was published.
#
# Note this format becomes redundant once the caching infrasture is able to
# honour caching headers on upstream 404 responses.
class PublishingApiPresenters::ComingSoon
attr_reader :edition, :update_type
def initialize(edition, options = {})
@edition = edition
@update_type = options[:update_type] || default_update_type
end
def base_path
Whitehall.url_maker.public_document_path(edition)
end
def as_json
{
base_path: base_path,
publishing_app: 'whitehall',
rendering_app: 'whitehall-frontend',
format: 'coming_soon',
title: 'Coming soon',
locale: I18n.locale.to_s,
update_type: update_type,
details: {
publish_time: edition.scheduled_publication,
},
routes: [
{
path: base_path,
type: "exact"
}
]
}
end
private
def default_update_type
'major'
end
end
|
class MuseumFinder::Scraper
def self.get_page
Nokogiri::HTML(open("https://www.si.edu/museums"))
end
def self.scrape_landing_page
museums_array = []
landing_page = self.get_page.css("div.content")
landing_page.css("div.b-text-wrapper").each do |museum|
name = museum.css("h3.title").text
url = "https://www.si.edu#{museum.css("h3.title a").attribute("href").text}"
location = museum.css("p.location").children[0].text.delete("\n").strip
museum = {:name => name, :url => url, :location => location}
museums_array << museum
end
museums_array
end
def self.scrape_museum_page(url)
doc = Nokogiri::HTML(open(url))
full_name = doc.css("h1.page-title").text
hours = doc.css("div.location-hours").text.gsub(/\r\n/," - ").strip
admission = doc.css("div.location-admission").text.delete("\n").strip
description = doc.css("div.info p").children[0].text
highlights = doc.css("div.info p").children[1].text
museum_listing = {:full_name => full_name, :hours => hours, :admission => admission, :description => description, :highlights => highlights}
museum_listing
end
end
|
Pod::Spec.new do |s|
version = "0.1.1"
s.name = "HXSlider"
s.version = version
s.summary = "HXSlider is a slider of special tailor-made."
s.homepage = "https://github.com/CapriHuang/HXSpec"
s.author = { "CapriHuang" => "1187395293@qq.com" }
s.source = { :git => "https://github.com/CapriHuang/HXSlider.git", :tag => '0.1.1' }
s.platform = :ios, '7.0'
s.source_files = 'HXSlider/*'
s.requires_arc = true
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.dependency 'Masonry'
s.dependency 'ReactiveCocoa'
end
|
# == Schema Information
#
# Table name: series
#
# id :integer not null, primary key
# title :string not null
# year :integer not null
# description :text not null
# avg_rating :integer default(0)
# created_at :datetime not null
# updated_at :datetime not null
# image_file_name :string
# image_content_type :string
# image_file_size :integer
# image_updated_at :datetime
# movie :boolean default(FALSE)
#
class Serie < ActiveRecord::Base
has_attached_file :image, styles: { medium: "226.23x127.25", thumb: "85x50" }, default_url: "default_logo.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
validates :title, :description, :year, presence: true
has_many :series_genres, dependent: :destroy
has_many :genres, through: :series_genres, source: :genre
has_many :episodes, dependent: :destroy
has_many :favorites, dependent: :destroy
has_many :reviews, dependent: :destroy
def self.all_ratings
ratings = {}
self
.select('series.*, AVG(reviews.rating) AS avg_rating')
.joins("LEFT OUTER JOIN reviews ON reviews.serie_id = series.id")
.group('series.id')
.each do |s|
ratings[s.id] = s.avg_rating
end
ratings
end
def get_avg_rating
reviews.select('AVG(rating) as avg_rating').group(:serie_id)
end
def user_rating(user)
reviews.select('rating').where('user_id = ?', user.id)
end
end
|
# frozen_string_literal: true
module Docx #:nodoc:
VERSION = '0.6.2'
end
|
class AddRowsToProcessToImport < ActiveRecord::Migration
def change
add_column :imports, :rows_to_process, :integer
end
end
|
require 'byebug'
class Sudoku
def initialize(board_string)
@backtrack_array = board_string.to_s.split("").map { |digit| digit.to_i }
@backtrack_board = @backtrack_array.each_slice(9).to_a
@board_horizontal = Marshal.load(Marshal.dump(@backtrack_board))
@horizontal_arr = Marshal.load(Marshal.dump(@backtrack_array))
@backtrack_squares = []
square_arr = Marshal.load(Marshal.dump(@board_horizontal))
3.times do
3.times do
temp_board = []
for i in (0..2)
selected = square_arr[i].take(3)
selected.each {|x| temp_board << x}
square_arr[i] = square_arr[i].drop(3)
end
@backtrack_squares << temp_board
end
square_arr = square_arr.drop(3)
end
@board_squares = Marshal.load(Marshal.dump(@backtrack_squares))
@counter = @horizontal_arr.count(0)
@squares_x = [[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 0, 0, 1, 1, 1, 2, 2, 2],
[3, 3, 3, 4, 4, 4, 5, 5, 5],
[3, 3, 3, 4, 4, 4, 5, 5, 5],
[3, 3, 3, 4, 4, 4, 5, 5, 5],
[6, 6, 6, 7, 7, 7, 8, 8, 8],
[6, 6, 6, 7, 7, 7, 8, 8, 8],
[6, 6, 6, 7, 7, 7, 8, 8, 8]]
@squares_y = [[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8],
[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8],
[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8]]
end
def locate(value)
x = value / 9
y = value % 9
if x < 3
return @board_squares[0] if y < 3
return @board_squares[1] if y < 6
return @board_squares[2] if y < 9
elsif x < 6
return @board_squares[3] if y < 3
return @board_squares[4] if y < 6
return @board_squares[5] if y < 9
elsif x < 9
return @board_squares[6] if y < 3
return @board_squares[7] if y < 6
return @board_squares[8] if y < 9
end
end
def multiple?(board)
count = 0
board.each do |row|
if row.uniq.length == row.length && row.include?(0) == false
count += 1
else return false
end
end
return true if count == 9
end
def run_through
10.times do
@counter = @horizontal_arr.count(0)
zeros = []
@horizontal_arr.each_with_index {|value, place| zeros << place if value == 0}
zeros.each do |x|
possible = [1, 2, 3, 4, 5, 6, 7, 8, 9]
possible -= @board_horizontal[x/9]
possible -= @board_horizontal.transpose[x%9]
position = locate(x)
possible -= position
if possible.length == 1
@board_horizontal[x/9][x%9] = possible[0]
@board_squares[@squares_x[x/9][x%9]][@squares_y[x/9][x%9]] = possible[0]
@counter -= 1
zeros -= [x]
end
end
@horizontal_arr = @board_horizontal.flatten
end
end
def solve!
boards_check = false
until boards_check == true
@board_horizontal = Marshal.load(Marshal.dump(@backtrack_board))
@horizontal_arr = Marshal.load(Marshal.dump(@backtrack_array))
@board_squares = Marshal.load(Marshal.dump(@backtrack_squares))
run_through
@guess_counter = @horizontal_arr.count(0)
if @counter == 0
return @board_horizontal
end
@guess_counter = @horizontal_arr.count(0)
zeros = []
@horizontal_arr.each_with_index {|value, place| zeros << place if value == 0}
zeros.each do |x|
possible = [1, 2, 3, 4, 5, 6, 7, 8, 9]
possible -= @board_horizontal[x/9]
possible -= @board_horizontal.transpose[x%9]
position = locate(x)
possible -= position
if possible.empty? == false
guess = possible.sample
@board_horizontal[x/9][x%9] = guess
@board_squares[@squares_x[x/9][x%9]][@squares_y[x/9][x%9]] = guess
possible -= [possible.sample]
zeros -= [x]
end
run_through
if multiple?(@board_horizontal) == true && multiple?(@board_horizontal.transpose) == true && multiple?(@board_squares) == true
boards_check = true
end
end
end
end
# Returns a string representing the current state of the board
# Don't spend too much time on this method; flag someone from staff
# if you are.
def board
@board_horizontal.flatten.join("")
end
end
# The file has newlines at the end of each line, so we call
# String#chomp to remove them.
#board_string = File.readlines('sample.unsolved.txt').first.chomp
game = Sudoku.new('096040001100060004504810390007950043030080000405023018010630059059070830003590007')
# Remember: this will just fill out what it can and not "guess"
game.solve!
puts game.board |
class Contract < ActiveRecord::Base
extend BaseModel
has_many :agreements
has_many :nations, :through => :agreements
has_many :aids
validates_presence_of :buyer_id, :seller_id
after_initialize :set_defaults
after_create :add_to_agreements, :find_aid
after_save :update_money_paid, :update_tech_paid
after_save :create_new_if_recurring
scope :buyer_id, ->(buyer_id) { where(:buyer_id => buyer_id) }
scope :seller_id, ->(seller_id) { where(:seller_id => seller_id) }
scope :started_before, ->(date) { where("start_date <= ?", date) }
scope :due_in, ->(days) { where("next_payment_date <= ?", days.days.from_now) }
def set_defaults
self.money_paid ||= 0
self.tech_paid ||= 0
end
def add_to_agreements
Agreement.find_or_create_by_nation_id_and_contract_id(buyer_id, id)
Agreement.find_or_create_by_nation_id_and_contract_id(seller_id, id)
end
def find_aid
ids = [buyer_id, seller_id]
self.aids = Aid.after_or_on(start_date).sender(ids).recipient(ids)
end
def create_new_if_recurring
if recurring? && inactive?
new_contract = self.dup
new_contract.update_attributes(:start_date => next_payment_date, :money_paid => 0, :tech_paid => 0)
new_contract.save!
end
end
def update_money_paid
update_attribute :money_paid, aids.approved.sum(:money)
end
def update_tech_paid
update_attribute :tech_paid, aids.approved.sum(:tech)
end
def money_owed
total_money - money_paid
end
def tech_owed
total_tech - tech_paid
end
def last_payment
aids.order(:sent_date).last
end
def last_payment_date
last_payment ? last_payment.sent_date.to_date : nil
end
def next_payment_date
last_payment_date ? last_payment_date + 10 : start_date.to_date
end
def buyer
Nation.find(buyer_id)
end
def seller
Nation.find(seller_id)
end
def due_today?
next_payment_date == Date.today
end
def overdue?
next_payment_date < Date.today
end
def inactive?
money_owed == 0 and tech_owed == 0
end
def active?
!inactive?
end
def self.current_contract(ids, date)
active.started_before(date).where(:buyer_id => ids, :seller_id => ids).limit(1).first
end
def self.method_missing(m, *args, &block)
if method_defined? "#{m.to_s}?"
# Define a new class method that will return all of the elements of
# the model that match some instance boolean method, i.e, active = scope_by(:active?)
define_singleton_method m do
scope_by "#{m.to_s}?".to_sym
end
send m
else
super
end
end
end
|
module Rspec
class StrategyGenerator < ::Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
def create_spec_file
template(
'strategy_rspec.rb',
File.join('spec/strategies', "#{singular_name}_strategy_spec.rb")
)
end
end
end
|
require 'rails_helper'
RSpec.feature "User views all artists" do
scenario "they visit artists index" do
artist1_name = "Bob Marley"
artist1_image_path = "http://cps-static.rovicorp.com/3/JPG_400/MI0003/146/MI0003146038.jpg"
Artist.create(name: artist1_name, image_path: artist1_image_path)
artist2_name = "Elvis Presley"
artist2_image_path = "https://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&uact=8&ved=0ahUKEwjn-cO5nuXPAhXkx4MKHV-cDokQjRwIBw&url=https%3A%2F%2Fwww.graceland.com%2Felvis%2Fbiography.aspx&psig=AFQjCNHF4JqcOm3Lxqhj-u8EgYLZRe4jaA&ust=1476910485226796"
Artist.create(name: artist2_name, image_path: artist2_image_path)
visit '/artists'
expect(page).to have_content artist1_name
expect(page).to have_content artist2_name
end
end
|
class GenerateDetailedTermReport
attr_accessor :over_marks, :fetch_report_headers
attr_accessor :exam_max_marks
def initialize(param)
@term = AssessmentTerm.find param[:exam].split('_').last
@param = param
@batch = Batch.find @param[:batch]
load_header_data
end
def fetch_report_data
@exam_max_marks = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
@score_hash = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
@studentwise_score = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
@mark_hash = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
@students = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
overrided_marks = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
assessment_groups = @term.assessment_groups
assessment_group_batches = AssessmentGroupBatch.all(:include=>:converted_assessment_marks,:conditions=>["batch_id=? and assessment_group_id in (?)",@batch.id,assessment_groups.collect(&:id)])
subject_codes = @batch.subjects.collect(&:code)
assessment_groups.each do |ag|
overrided_marks[ag.id] = ag.override_assessment_marks.find(:all,
:joins=>"INNER JOIN courses on courses.id = override_assessment_marks.course_id INNER JOIN batches on batches.course_id = courses.id INNER JOIN subjects ON subjects.name = override_assessment_marks.subject_name AND subjects.school_id = #{MultiSchool.current_school.id} AND subjects.batch_id = #{@batch.id}",
:select=>'override_assessment_marks.*,subjects.id subject_id',
:conditions=>["subject_code in (?)",subject_codes]).group_by(&:subject_id)
@agb = assessment_group_batches.to_a.find{|agb| agb.assessment_group_id == ag.id }
next if @agb.nil?
ass_marks = @agb.converted_assessment_marks
@batch.effective_students.each do |student|
student_marks = ass_marks.to_a.select{|am| am.student_id == student.s_id}
student_marks.each do |obj|
@students[obj.markable_id][ag.id][obj.student_id] = true
if (@param[:type] == "planner" or ag.type == "DerivedAssessmentGroup" or !ag.is_single_mark_entry) and @param[:type] != "percent"
maximum_marks = (overrided_marks[ag.id][obj.markable_id.to_s].present? ? overrided_marks[ag.id][obj.markable_id.to_s].first.maximum_marks.to_f : ag.maximum_marks)
@exam_max_marks[obj.markable_id][ag.id] = ag.maximum_marks
if ag.scoring_type == 1
@mark_hash[obj.markable_id][obj.student_id][ag.id][:mark] = obj.grade.present? ? obj.grade : obj.mark.to_f
@score_hash[ag.id][obj.markable_id][obj.student_id][:mark] = obj.grade.present? ? obj.grade : obj.mark.to_f
@studentwise_score[obj.student_id][obj.markable_id][ag.id] = {:mark => obj.grade.present? ? obj.grade : obj.mark.to_f, :max_mark => maximum_marks}
# @studentwise_score[obj.student_id][obj.markable_id][ag.id][:max_mark] = @over_marks[ag.id] if @over_marks[ag.id].present?
elsif ag.scoring_type == 2
@mark_hash[ag.id][obj.markable_id][obj.student_id][:mark] = obj.mark.to_f
@score_hash[ag.id][obj.markable_id][obj.student_id][:mark] = obj.grade
else
@mark_hash[obj.markable_id][obj.student_id][ag.id][:mark] = obj.grade.present? ? (obj.mark.present? ? "#{obj.mark.to_f} (#{obj.grade})" : "#{obj.grade}") : obj.mark.to_f
@score_hash[ag.id][obj.markable_id][obj.student_id][:mark] = obj.grade.present? ? (obj.mark.present? ? "#{obj.mark.to_f} (#{obj.grade})" : "#{obj.grade}") : obj.mark.to_f
@studentwise_score[obj.student_id][obj.markable_id][ag.id] = {:mark=>obj.grade.present? ? (obj.mark.present? ? "#{obj.mark.to_f} (#{obj.grade})" : "#{obj.grade}") : obj.mark.to_f , :max_mark => maximum_marks}
# @studentwise_score[obj.student_id][obj.markable_id][ag.id] = {:mark=>obj.mark.present? ? obj.mark.to_f : nil, :max_mark => @over_marks[ag.id]} if @over_marks[ag.id].present?
end
elsif @param[:type] == "exam"
max_mark = obj.assessment_group_batch.subject_assessments.to_a.find{|sa| sa.subject_id == obj.markable_id}.try(:maximum_marks).to_f
@exam_max_marks[obj.markable_id][ag.id] = max_mark
if obj.actual_mark.present?
case ag.scoring_type
when 1
@mark_hash[obj.markable_id][obj.student_id][ag.id] = {:mark =>obj.actual_mark[:grade].present? ? obj.actual_mark[:grade] : obj.actual_mark[:mark], :max_mark=>max_mark}
@score_hash[ag.id][obj.markable_id][obj.student_id] = {:mark=>obj.actual_mark[:grade].present? ? obj.actual_mark[:grade] : obj.actual_mark[:mark], :max_mark=>max_mark}
@studentwise_score[obj.student_id][obj.markable_id][ag.id] = {:mark => obj.actual_mark[:grade].present? ? obj.actual_mark[:grade] : obj.actual_mark[:mark], :max_mark=>max_mark }
when 2
@studentwise_score[obj.student_id][obj.markable_id][ag.id] = {:mark => obj.actual_mark[:mark], :max_mark=>max_mark }
@score_hash[ag.id][obj.markable_id][obj.student_id][:mark] = obj.actual_mark[:grade]
when 3
@mark_hash[obj.markable_id][obj.student_id][ag.id][:mark] = obj.actual_mark[:mark]
@score_hash[ag.id][obj.markable_id][obj.student_id][:mark] = "#{obj.actual_mark[:mark]}(#{obj.actual_mark[:grade]})"
@studentwise_score[obj.student_id][obj.markable_id][ag.id] = { :mark=>obj.actual_mark[:mark], :grade=>obj.actual_mark[:grade], :max_mark=>max_mark }
end
end
elsif @param[:type] == "percent"
maximum_marks = (overrided_marks[ag.id][obj.markable_id.to_s].present? ? overrided_marks[ag.id][obj.markable_id.to_s].first.maximum_marks.to_f : ag.maximum_marks)
@mark_hash[obj.markable_id][obj.student_id][ag.id] = {:mark => (obj.mark.to_f*100)/maximum_marks } if [1,3].include? ag.scoring_type
@score_hash[ag.id][obj.markable_id][obj.student_id][:mark] = obj.mark.present? ? "#{((obj.mark.to_f*100)/maximum_marks).round(2)}%" : "-" if [1,3].include? ag.scoring_type
@studentwise_score[obj.student_id][obj.markable_id][ag.id][:mark] = (obj.mark.to_f*100)/maximum_marks if [1,3].include? ag.scoring_type
@score_hash[ag.id][obj.markable_id][obj.student_id][:mark] = obj.grade || "-" if ag.scoring_type == 2
end
end
end
end
@score_hash
end
def load_header_data # fetch_report_headers
agbs = @batch.assessment_group_batches.collect(&:id)
@ags = ConvertedAssessmentMark.all(
:conditions=>["assessment_group_batch_id in (?) and assessment_groups.parent_id = ?",agbs,@term.id],
:joins=>[:assessment_group],
:select=>"markable_id s_id,assessment_groups.name ag_name,assessment_groups.type ag_type,assessment_groups.is_single_mark_entry,assessment_groups.id ag_id,assessment_groups.maximum_marks max_mark, assessment_groups.scoring_type scoring_type",
:group=>['s_id,ag_id'])
@over_marks = OverrideAssessmentMark.all(:conditions => {:course_id => @batch.course_id, :assessment_group_id => @ags.collect(&:ag_id)}).group_by(&:assessment_group_id)
@fetch_report_headers = @ags.group_by(&:s_id)
end
def calculate_total
subjects_total = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
@studentwise_score.each_pair do |student_id,subject|
total_mark = 0
max_total = 0
subject.each_pair do |subject_id,val|
val.each_pair do |key,value|
total_mark += value[:mark].to_f if value[:mark].present?
max_total += value[:max_mark].to_f if value[:max_mark].present?
end
subjects_total[student_id] = {:total=> total_mark, :percentage => (max_total.zero? ? nil : (total_mark*100)/max_total) }
end
end
subjects_total
end
def find_rank
subjects_total = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
rank_hash = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
total = []
arr = []
@studentwise_score.each_pair do |student_id,subject|
total_mark = 0
max_total = 0
subject.each_pair do |subject_id,val|
val.each_pair do |key,value|
total_mark += value[:mark].to_f if value[:mark].present?
max_total += value[:max_mark].to_f if value[:max_mark].present?
end
end
subjects_total[student_id] = (total_mark*100)/max_total unless max_total.zero?
end
if subjects_total.present?
subjects_total = subjects_total.sort_by {|_, value| value}.reverse
total = subjects_total.map{|x| x.last}
sorted = total.sort.uniq.reverse
rank = total.map{|e| sorted.index(e) + 1}
rank.each_with_index do |r,i|
arr<<[subjects_total[i].first,r]
end
arr.each do |obj|
rank_hash[obj.first]={:rank=>obj.last}
end
end
rank_hash
end
def calculate_average
avg = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
@mark_hash.each_pair do |sub_id,stud|
exam_groups = []
total_mark = {}
stud.each_pair do |stud_id,val|
val.each_pair do |key,value|
total_mark[key] = total_mark[key].present? ? total_mark[key] : []
total_mark[key] << value[:mark]
exam_groups << key
end
end
exam_groups.uniq.each do |eg|
avg[sub_id][eg] = total_mark[eg].map(&:to_f).sum / @students[sub_id][eg].keys.count if total_mark[eg].present?
end
end
avg
end
def find_highest
highest = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
@mark_hash.each_pair do |sub_id,stud|
exam_groups = []
total_mark = {}
stud.each_pair do |stud_id,val|
val.each_pair do |key,value|
total_mark[key] = total_mark[key] || []
total_mark[key] << value[:mark]
exam_groups << key
end
end
exam_groups.uniq.each do |eg|
highest[sub_id][eg] = total_mark[eg].sort.last
end
end
highest
end
end |
class PropertiesController < ApplicationController
def index
@properties = Property.all
end
def new
@property = Property.new
end
def create
@property = Property.new(property_params)
if @property.save
redirect_to root_path
else
render 'new'
end
end
def edit
@property = Property.find_by(id: params[:id])
end
def update
@property = Property.find_by(id: params[:id])
if @property.update(property_params)
redirect_to root_path
else
render 'edit'
end
end
def destroy
property = Property.find_by(id: params[:id])
property.destroy
redirect_to root_path
end
private
def property_params
params.require(:property).permit(:company, :neighborhood, :address, :phone)
end
end
|
class Symbol
# From https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-camelize
def camelize
self.to_s.sub(/^[a-z\d]*/) { |m| m.capitalize }
.gsub(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{$2.capitalize}" }
.gsub('/', '::')
end
def constantize
self.camelize.constantize
end
end
|
require 'test_helper'
module JackCompiler
module Transformer
class TestParserProcessor < Minitest::Test
def test_analyze_symbols
parse_node = VisitorTestHelper.prepare_tree(<<~SOURCE, root_node: :class)
class Bill {
static integer tax_rate;
field integer total;
field String contact_name;
constructor Bill new(String name) {
let total = 0;
let contact_name = name;
return this;
}
function void set_tax_rate(integer rate) {
let tax_rate = rate;
}
method void add(Product prod, integer count) {
var integer price;
let price = prod.price();
let total = price * count;
return;
}
method integer summarize() {
var Float gross;
let gross = Math.to_float(total * (100 +tax_rate)) / Math.to_float(100);
return Math.floor(gross);
}
}
SOURCE
processor = JackCompiler::Transformer::Processor.new(parse_node)
processor.transform!
processor.analyze_symbols
table = processor.symbol_table
assert_equal :Bill, table.class_name
subroutines = table.subroutine_ids
assert_equal %i(new set_tax_rate add summarize), subroutines.keys
assert_equal [:constructor, :Bill],
[
subroutines[:new].kind,
subroutines[:new].return_type,
]
assert_equal [:function, :void],
[
subroutines[:set_tax_rate].kind,
subroutines[:set_tax_rate].return_type,
]
assert_equal [:method, :void],
[
subroutines[:add].kind,
subroutines[:add].return_type,
]
assert_equal [:method, :integer],
[
subroutines[:summarize].kind,
subroutines[:summarize].return_type,
]
# for class vars
registered_vars = table.variable_ids[:class]
assert_equal 3, registered_vars.size
assert_equal [:static, :integer, 0],
[
registered_vars[:tax_rate].kind,
registered_vars[:tax_rate].type,
registered_vars[:tax_rate].number,
]
assert_equal [:field, :integer, 0],
[
registered_vars[:total].kind,
registered_vars[:total].type,
registered_vars[:total].number,
]
assert_equal [:field, :String, 1],
[
registered_vars[:contact_name].kind,
registered_vars[:contact_name].type,
registered_vars[:contact_name].number,
]
# for .new
registered_vars = table.variable_ids[:new]
assert_equal 1, registered_vars.size
assert_equal [:argument, :String, 0],
[
registered_vars[:name].kind,
registered_vars[:name].type,
registered_vars[:name].number,
]
# for .set_tax_rate
registered_vars = table.variable_ids[:set_tax_rate]
assert_equal 1, registered_vars.size
assert_equal [:argument, :integer, 0],
[
registered_vars[:rate].kind,
registered_vars[:rate].type,
registered_vars[:rate].number,
]
# for #add
registered_vars = table.variable_ids[:add]
assert_equal 4, registered_vars.size
assert_equal [:argument, :Bill, 0],
[
registered_vars[:this].kind,
registered_vars[:this].type,
registered_vars[:this].number,
]
assert_equal [:argument, :Product, 1],
[
registered_vars[:prod].kind,
registered_vars[:prod].type,
registered_vars[:prod].number,
]
assert_equal [:argument, :integer, 2],
[
registered_vars[:count].kind,
registered_vars[:count].type,
registered_vars[:count].number,
]
assert_equal [:local, :integer, 0],
[
registered_vars[:price].kind,
registered_vars[:price].type,
registered_vars[:price].number,
]
# for #summarize
registered_vars = table.variable_ids[:summarize]
assert_equal 2, registered_vars.size
assert_equal [:argument, :Bill, 0],
[
registered_vars[:this].kind,
registered_vars[:this].type,
registered_vars[:this].number,
]
assert_equal [:local, :Float, 0],
[
registered_vars[:gross].kind,
registered_vars[:gross].type,
registered_vars[:gross].number,
]
end
def test_compile
parse_node = VisitorTestHelper.prepare_tree(<<~SOURCE, root_node: :class)
class Bill {
static integer tax_rate;
field integer total;
field String contact_name;
constructor Bill new(String name) {
let total = 0;
let contact_name = name;
return this;
}
function void set_tax_rate(integer rate) {
let tax_rate = rate;
return;
}
method boolean add(Product prod, integer count) {
var integer price;
let price = prod.price();
let total = price * count;
return true;
}
method boolean add_list(List list){
var integer i;
var Array order;
var Product prod;
var integer count;
let i = 0;
while (list.has_order(i)) {
let order = list.get_order(i);
let prod = order[0];
let count = order[1];
do add(prod, count);
let i = i + 1;
}
if(i=0) {
return false;
} else {
return true;
}
}
method integer summarize() {
var Float gross;
let gross = Math.to_float(total * (100 +tax_rate)) / Math.to_float(100);
return Math.floor(gross);
}
}
SOURCE
processor = JackCompiler::Transformer::Processor.new(parse_node)
processor.transform!
processor.analyze_symbols
processor.symbol_table
vm_code = processor.compile
assert_equal <<~VMCODE.chomp, vm_code.join("\n")
function Bill.new 0
push constant 2
call Memory.alloc 1
pop pointer 0
push constant 0
pop this 0
push argument 0
pop this 1
push pointer 0
return
function Bill.set_tax_rate 0
push argument 0
pop static 0
push constant 0
return
function Bill.add 1
push argument 0
pop pointer 0
push argument 1
call Product.price 1
pop local 0
push local 0
push argument 2
call Math.multiply 2
pop this 0
push constant 1
neg
return
function Bill.add_list 4
push argument 0
pop pointer 0
push constant 0
pop local 0
label label1.while_start
push argument 1
push local 0
call List.has_order 2
if-goto label1.while
goto label1.while_end
label label1.while
push argument 1
push local 0
call List.get_order 2
pop local 1
push constant 0
push local 1
add
pop pointer 1
push that 0
pop local 2
push constant 1
push local 1
add
pop pointer 1
push that 0
pop local 3
push pointer 0
push local 2
push local 3
call Bill.add 3
pop temp 0
push local 0
push constant 1
add
pop local 0
goto label1.while_start
label label1.while_end
push local 0
push constant 0
eq
if-goto label2.if
push constant 1
neg
return
goto label2.if_end
label label2.if
push constant 0
return
label label2.if_end
function Bill.summarize 1
push argument 0
pop pointer 0
push this 0
push constant 100
push static 0
add
call Math.multiply 2
call Math.to_float 1
push constant 100
call Math.to_float 1
call Math.divide 2
pop local 0
push local 0
call Math.floor 1
return
VMCODE
end
end
end
end
|
class Comment < ActiveRecord::Base
belongs_to :article
validates :name, :email, :body, presence: true
validate :article_should_be_published
after_create :send_comment_email
private
def article_should_be_published
if article && !article.published?
errors.add(:article_id, "is not published yet")
end
end
def send_comment_email
Notifier.comment_added(self).deliver_now
end
end
|
class ApiEmployee
include HTTParty
base_uri CONFIG['url_api']
headers "Content-Type" => "application/json"
def self.create(employee, authorization)
post("/empregado/cadastrar", headers: { "Authorization" => authorization }, body: employee.to_json)
end
def self.list_all(authorization)
get("/empregado/list_all", headers: { "Authorization" => authorization })
end
def self.list(employee_id, authorization)
get("/empregado/list/#{employee_id}", headers: { "Authorization" => authorization })
end
def self.update(employee_id, employee, authorization)
put("/empregado/alterar/#{employee_id}", headers: { "Authorization" => authorization }, body: employee.to_json)
end
end |
# == Schema Information
#
# Table name: awards
#
# id :integer not null, primary key
# year :integer
# body :text
# paper_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# pinned :boolean
#
class Award < ActiveRecord::Base
belongs_to :paper
def as_json(options)
{
id: self.id,
year: self.year,
body: self.body,
pinned: self.pinned,
paper: self.paper.present? ? self.paper.as_json(options) : {}
}
end
end
|
class UsersController < ApplicationController
def edit
@user = User.find(params[:id])
@page = params[:page]
end
def update
@user = User.find(params[:id])
@user.update(user_param)
redirect_to params[:user][:page].to_sym
end
private
def user_param
params.require(:user).permit(:name, :gender, :region)
end
end
|
class Api::CurrentSeason::PicksController < Api::CurrentSeasonController
expose(:character) { Character.find params[:character_id] }
expose(:current_picks) { character.picks.map &CurrentPick.method(:new) }
def create
team = Team.find params[:team_id]
week = character.season.weeks.find_by number: params[:week_number]
pick = character.picks.build team: team, week: week
if pick.save
render :index, status: :created
end
end
end
|
# typed: true
# frozen_string_literal: true
$LOAD_PATH.unshift File.expand_path('../lib', __dir__)
require 'simplecov'
SimpleCov.start
require 'ffprober'
require 'minitest/autorun'
def fake_ffprobe_version_path
"#{File.expand_path(__dir__)}/fake_ffprobe_version"
end
def fake_ffprobe_output_path
"#{File.expand_path(__dir__)}/fake_ffprobe_output"
end
def assets_path
File.expand_path('assets', __dir__)
end
|
class AddBookingRefToCartItems < ActiveRecord::Migration[5.1]
def change
add_reference :cart_items, :booking, foreign_key: true
end
end
|
# create a hash that expresses the frequency with which
# each letter occurs in this string
statement = "The Flintstones Rock"
h = {}
statement.chars.each do |x|
h[x] = statement.count(x) if x != " "
end
puts h
puts statement |
class ShowResource < BaseResource
SHOW_CONTENT_TYPE = "application/vnd.com.example.show+json"
SHOW_CONTENT_TYPE_V2 = "application/vnd.com.example.show-v2+json"
def content_types_provided
[
['text/html', :to_html],
[SHOW_CONTENT_TYPE, :to_show_json],
[SHOW_CONTENT_TYPE_V2, :to_show_json_v2]
]
end
def to_html
render_template('show.html', show)
end
def to_show_json
add_links({
:show => {
:name => show.name
}
}).to_json
end
def to_show_json_v2
add_links({
:show => show
}).to_json
end
def resource_exists?
!show.nil?
end
def allowed_methods
['OPTIONS', 'GET', 'DELETE']
end
def delete_resource
MODEL.delete_show(show.name)
true
end
def last_modified
show.last_modified
end
def generate_etag
content = show.name.dup
show.performances.each do |p|
content << p.date.strftime('%c')
content << p.seats.to_s
end
Digest::SHA1.hexdigest(content)
end
def add_links(json)
json[:links] = {
'performances' => "/shows/#{show.name}/performances"
}
json
end
end
|
class Artist
attr_accessor :name, :songs
@@all = []
def initialize(name)
@name = name
@songs =[]
end
def add_song(songname)
#song = Song.new(songname)
@songs << songname
end
def save
@@all << self
self
end
def self.all
@@all
end
def self.find_or_create_by_name(artist)
match = @@all.find do |x|
x.name == artist
end
if match == nil
match = Artist.new(artist).save
end
match
end
def print_songs
@songs.each do |song|
puts song.name
end
end
end
|
module XMLMunger
class NestedHash < Hash
#######
# Don't lose class type
#######
(Hash.instance_methods - Object.instance_methods).each do |m|
define_method(m) { |*args, &block|
result = super(*args, &block)
return NestedHash[result] if result.class == Hash
result
}
end
#######
# Map terminal hash values in a nested hash
# > nh = NestedHash[a: { c: 2 }, b: 1]
# => { a: { c: 2 }, b: 1 }
# > nh.transform { |value| value + 1 }
# => { a: { c: 3 }, b: 2 }
#######
def transform(&block)
# http://stackoverflow.com/questions/5189161/changing-every-value-in-a-hash-in-ruby
NestedHash[self.map { |key, value|
[key, case value.class.to_s
when 'Hash', 'NestedHash' then NestedHash[value].transform(&block)
else yield value
end]
}]
end
#######
# Map terminal hash values in a nested hash *with* route tracking
# > nh = NestedHash[a: { c: 2 }, b: 1]
# => { a: { c: 2 }, b: 1 }
# > nh.transform_with_route { |route, value| "#{route.join(' -> ')} -> #{value}" }
# => { a: { c: "a -> c -> 2" }, b: "b -> 1" }
#######
def transform_with_route(route = [], &block)
NestedHash[self.map { |key, value|
[key, case value.class.to_s
when 'Hash', 'NestedHash' then
NestedHash[value].transform_with_route(route.dup.concat([key]), &block)
else yield route.dup.concat([key]), value
end]
}]
end
#######
# Map terminal hash values in a nested hash to an array
# > nh = NestedHash[a: { c: 2 }, b: 1]
# => { a: { c: 2 }, b: 1 }
# > nh.map_values
# => [2, 1]
# > nh.map_values { |x| x + 1 }
# => [3, 2]
#######
def map_values(&block)
values = []
self.each { |key, value|
values.concat case value.class.to_s
when 'Hash', 'NestedHash' then NestedHash[value].map_values(&block)
else [block_given? ? yield(value) : value]
end
}
values
end
#######
# Map terminal hash values in a nested hash to an array *with* route tracking
# > nh = NestedHash[a: { c: 2 }, b: 1]
# => { a: { c: 2 }, b: 1 }
# > nh.map_values_with_route { |route, value| route << value**value }
# => [[:a, :c, 4], [:b, 1]]
#######
def map_values_with_route(route = [], &block)
values = []
self.each { |key, value|
route_copy = route.dup
values.concat case value.class.to_s
when 'Hash', 'NestedHash' then
NestedHash[value].map_values_with_route(route_copy.concat([key]), &block)
else [block_given? ? yield(route_copy.concat([key]), value) : route_copy.concat([key, value])]
end
}
values
end
end
end
|
class Licencia < ActiveRecord::Base
self.table_name = 'licencias'
self.inheritance_column = 'ruby_type'
self.primary_key = 'id'
if ActiveRecord::VERSION::STRING < '4.0.0' || defined?(ProtectedAttributes)
attr_accessible :id_empresa, :id_chofer, :cedula, :motivo, :fecha_desde, :fecha_hasta, :importe, :salario_vacacional
end
belongs_to :empresa, :foreign_key => 'id_empresa', :class_name => 'Empresa'
belongs_to :chofer, :foreign_key => 'id_chofer', :class_name => 'Chofer'
def get_motivo
if self.motivo == 0
return "LICENCIA REGLAMENTARIA"
end
if self.motivo == 1
return "DISSE"
end
if self.motivo == 2
return "BSE"
end
if self.motivo == 3
return "SEGURO DE PARO"
end
if self.motivo == 4
return "LICENCIA EXTRAORDINARIA"
end
return ""
end
end
|
# encoding: UTF-8
module CDI
module V1
module GameQuestions
class ReorderService < BaseReorderService
record_type ::GameQuestion
def record_error_key
:game_questions
end
end
end
end
end
|
class Comment < ApplicationRecord
belongs_to :betting_ticket
belongs_to :end_user
end
|
class CreateModelings < ActiveRecord::Migration
def up
create_table :modelings do |t|
t.integer :placement
t.timestamps
end
end
def down
drop_table :modelings
end
end
|
# -*- encoding: utf-8 -*-
require 'nkf'
class BusinessPartner < ActiveRecord::Base
before_create :set_default
include AutoTypeName
has_many :businesses, :conditions => ["businesses.deleted = 0"]
has_many :bp_pics, :conditions => ["bp_pics.deleted = 0"]
has_many :biz_offers, :conditions => ["biz_offers.deleted = 0"]
has_many :bp_members, :conditions => ["bp_members.deleted = 0"]
validates_presence_of :business_partner_name, :business_partner_short_name, :business_partner_name_kana
validates_uniqueness_of :business_partner_code, :case_sensitive => false, :allow_blank => true, :scope => [:deleted, :deleted_at]
validates_uniqueness_of :business_partner_name, :case_sensitive => false, :scope => [:deleted, :deleted_at]
def set_default
self.sales_code = "S" + SysConfig.get_seq_0('sales_code', 7)
end
def address
"#{address1}#{address2}"
end
def business_partner_code_name
self.sales_code + " " + business_partner_name
end
def basic_contract_concluded
resultConclude = ""
resultConclude += "甲" if basic_contract_first_party_status_type == 'concluded'
resultConclude += "乙" if basic_contract_second_party_status_type == 'concluded'
return resultConclude
end
def basic_contract_concluded_format
basic_contract_concluded.blank? ? "" : "[#{basic_contract_concluded}]"
end
def BusinessPartner.export_to_csv
csv_data = []
csv_data << "e-mail,Name,ZipCode,Prefecture,Address,Tel,Birthday,Occupation,取引先Id,担当者Id,グループ"
BpPic.all.each do |x|
csv_data << [x.email1, x.bp_pic_name,x.business_partner.business_partner_name, "", "", "", "", "", "", "", x.business_partner.id, x.id].join(',')
end
return NKF.nkf("-s", csv_data.join("\n"))
end
def BusinessPartner.import_from_csv(filename, prodmode=false)
File.open(filename, "r"){|file| import_from_csv_data(file, prodmode)}
end
def BusinessPartner.create_business_partner(companies, email, pic_name, company_name)
unless companies[company_name.upcase]
unless bp = BusinessPartner.where(:business_partner_name => company_name, :deleted => 0).first
bp = BusinessPartner.new
bp.business_partner_name = company_name
bp.business_partner_short_name = company_name
bp.business_partner_name_kana = company_name
bp.sales_status_type = 'listup'
bp.basic_contract_first_party_status_type ||= 'none'
bp.basic_contract_second_party_status_type ||= 'none'
if pic_name.include?('担当者')
bp.email = email
end
bp.created_user = 'import'
bp.updated_user = 'import'
bp.save!
end
companies[company_name.upcase] = [bp, {}]
end
return companies[company_name.upcase]
end
def BusinessPartner.create_bp_pic(companies, email, pic_name, company_name, memo = nil)
bp, pics = companies[company_name.upcase]
pic = BpPic.new
pic.business_partner_id = bp.id
pic.bp_pic_name = pic_name
pic.bp_pic_short_name = pic_name
pic.bp_pic_name_kana = pic_name
pic.email1 = email
pic.memo = memo
pic.working_status_type = 'working'
pic.created_user = 'import'
pic.updated_user = 'import'
begin
pic.save!
rescue ActiveRecord::RecordInvalid => e
Rails.logger.error e.message + e.backtrace.join("\n") + pic.inspect
end
return pic
end
def BusinessPartner.import_from_csv_data(readable_data, prodmode=false)
ActiveRecord::Base.transaction do
require 'csv'
companies = {}
bp_id_cache = []
bp_pic_id_cache = []
CSV.parse(NKF.nkf("-w", readable_data)).each do |row|
# Read email
email,pic_name,com,pref,address,tel,birth,occupa,bp_id,bp_pic_id,group = row
next if email.to_s.strip.blank?
next if email == 'e-mail'
email = StringUtil.to_test_address(email) unless prodmode
a,b = com.split(" ")
company_name = StringUtil.strip_with_full_size_space(a)
if pic_name =~ /(.*)様/
pic_name = $1
end
pic_name = StringUtil.strip_with_full_size_space(pic_name.to_s)
if bp_id.blank?
# bp新規登録
bp, names = create_business_partner(companies, email, pic_name, company_name)
bp_id = bp.id
bp_id_cache << bp.id
else
bp_id = bp_id.to_i
=begin
unless bp_id_cache.include? bp_id.to_i
bp_id_cache << bp_id.to_i
bp = Businesspartner.find(bp_id)
unless companies[bp.business_partner_name.upcase]
companies[bp.business_partner_name.upcase] = [bp, {}]
end
end
=end
end
if bp_pic_id.blank?
# bp_pic新規登録
pic = create_bp_pic(companies, email, pic_name, company_name, row[3..7].reject{|x| x.blank?}.join("\n"))
bp_pic_id = pic.id
bp_pic_id_cache << pic.id
else
bp_pic_id = bp_pic_id.to_i
=begin
unless bp_pic_id_cache.include? bp_pic_id.to_i
bp_pic_id_cache << bp_pic_id.to_i
pic = BpPic.find(bp_pic_id)
unless companies[company_name.upcase][pic.bp_pic_name.upcase]
companies[company_name.upcase][pic.bp_pic_name.upcase] = pic
end
end
=end
end
# グループ登録
unless group.blank?
unless bp_pic_group = BpPicGroup.where(:deleted => 0, :bp_pic_group_name => group).first
bp_pic_group = BpPicGroup.new
bp_pic_group.bp_pic_group_name = group
bp_pic_group.created_user = 'import'
bp_pic_group.updated_user = 'import'
bp_pic_group.save!
end
unless bp_pic_group_detail = BpPicGroupDetail.where(:bp_pic_group_id => :bp_pic_group_id, :bp_pic_id => bp_pic_id).first
bp_pic_group_detail = BpPicGroupDetail.new
bp_pic_group_detail.bp_pic_group_id = bp_pic_group.id
bp_pic_group_detail.bp_pic_id = bp_pic_id
bp_pic_group_detail.created_user = 'import'
bp_pic_group_detail.updated_user = 'import'
bp_pic_group_detail.save!
end
end
end
end
end
# 名刺管理アカウントから出力されたCSVファイルをインポート(google.csv)
def BusinessPartner.import_google_csv_data(readable_file, userlogin, prodmode=false)
BusinessPartnerGoogleImporter.import_google_csv_data(readable_file, userlogin, prodmode)
end
end
|
#
# Copyright (c) 2017 joshua stein <jcs@jcs.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
class Attachment < DBModel
self.table_name = "attachments"
before_create :generate_uuid_primary_key
belongs_to :cipher,
foreign_key: :cipher_uuid,
inverse_of: :attachments
def self.build_from_params(params)
Attachment.new(filename: params[:filename], size: params[:size],
file: params[:file])
end
def to_hash
{
"Id" => self.uuid,
"Url" => self.url,
"FileName" => self.filename.to_s,
"Size" => self.size,
"SizeName" => human_file_size,
"Object" => "attachment"
}
end
def url
"#{::ATTACHMENTS_URL}/#{self.cipher_uuid}/#{self.id}"
end
private
def human_file_size
ActiveSupport::NumberHelper.number_to_human_size(self.size)
end
end
|
class AddAverageScoreToLearningTrack < ActiveRecord::Migration
def change
add_column :learning_tracks, :average_score, :float, :null => false, :default => 0
end
end
|
class ServiceMappingController < ApplicationController
before_action :logged_in_user, only: [:destroy, :create, :update, :list, :search, :find]
def create
if params.has_key?(:id_station)
if current_user.check_permission params[:id_station], params[:table_id], 1
@station = Station.find params[:id_station]
@s_id = Service.find_by(id: params[:s_id], sname: params[:sname], station_id: @station.id)
if !@s_id.nil?
@s_id = @s_id.id
end
@r_id = Room.find_by(id: params[:r_id], name: params[:rname], station_id: @station.id)
if !@r_id.nil?
@r_id = @r_id.id
end
@position = ServiceMap.new(station_id: @station.id, service_id: @s_id, sname: params[:sname], rname: params[:rname], room_id: @r_id)
if @position.save
render json: @position
else
render json: @position.errors, status: :unprocessable_entity
end
else
head :no_content
end
else
if has_station?
@station = Station.find_by(user_id: current_user.id)
@s_id = Service.find_by(id: params[:s_id], sname: params[:sname], station_id: @station.id)
if !@s_id.nil?
@s_id = @s_id.id
end
@r_id = Room.find_by(id: params[:r_id], name: params[:rname], station_id: @station.id)
if !@r_id.nil?
@r_id = @r_id.id
end
@position = ServiceMap.new(station_id: @station.id, service_id: @s_id, sname: params[:sname], rname: params[:rname], room_id: @r_id)
if @position.save
render json: @position
else
render json: @position.errors, status: :unprocessable_entity
end
else
redirect_to root_path
end
end
end
def update
if has_station?
@station = Station.find_by(user_id: current_user.id)
if params.has_key?(:id)
@posmap = ServiceMap.find(params[:id])
if @posmap.station_id == @station.id
@s_id = Service.find_by(id: params[:s_id], sname: params[:sname], station_id: @station.id)
if !@s_id.nil?
@s_id = @s_id.id
end
@r_id = Room.find_by(id: params[:r_id], name: params[:rname], station_id: @station.id)
if !@r_id.nil?
@r_id = @r_id.id
end
if @posmap.update(station_id: @station.id, service_id: @s_id, sname: params[:sname], rname: params[:rname], room_id: @r_id)
render json: @posmap
else
render json: @posmap.errors, status: :unprocessable_entity
end
end
end
else
redirect_to root_path
end
end
def destroy
if params.has_key?(:id_station)
if current_user.check_permission params[:id_station], params[:table_id], 3
@station = Station.find params[:id_station]
@position = ServiceMap.find(params[:id])
if @position.station_id == @station.id
@position.destroy
head :no_content
end
end
else
if has_station?
@station = Station.find_by(user_id: current_user.id)
@position = ServiceMap.find(params[:id])
if @position.station_id == @station.id
@position.destroy
head :no_content
end
else
redirect_to root_path
end
end
end
def list
if has_station?
@station = Station.find_by(user_id: current_user.id)
@data = []
@data[0] = ServiceMap.where(station_id: @station.id)
render json: @data
else
redirect_to root_path
end
end
def search
if params.has_key?(:id_station)
if current_user.check_permission params[:id_station], params[:table_id], 4
@station = Station.find params[:id_station]
if params.has_key?(:sname)
@supplier = ServiceMap.where("sname LIKE ? and station_id = ?" , "%#{params[:sname]}%", @station.id).group(:sname).limit(5)
render json:@supplier
elsif params.has_key?(:rname)
@supplier = ServiceMap.where("rname LIKE ? and station_id = ?" , "%#{params[:rname]}%", @station.id).group(:rname).limit(5)
render json:@supplier
end
else
head :no_content
end
else
if has_station?
@station = Station.find_by(user_id: current_user.id)
if params.has_key?(:sname)
@supplier = ServiceMap.where("sname LIKE ? and station_id = ?" , "%#{params[:sname]}%", @station.id).group(:sname).limit(5)
render json:@supplier
elsif params.has_key?(:rname)
@supplier = ServiceMap.where("rname LIKE ? and station_id = ?" , "%#{params[:rname]}%", @station.id).group(:rname).limit(5)
render json:@supplier
end
else
redirect_to root_path
end
end
end
def find
if params.has_key?(:id_station)
if current_user.check_permission params[:id_station], params[:table_id], 4
@station = Station.find params[:id_station]
if params.has_key?(:sname)
@supplier = ServiceMap.where("sname LIKE ? and station_id = ?" , "%#{params[:sname]}%", @station.id)
render json:@supplier
elsif params.has_key?(:rname)
@supplier = ServiceMap.where("rname LIKE ? and station_id = ?" , "%#{params[:rname]}%", @station.id)
render json:@supplier
end
else
head :no_content
end
else
if has_station?
@station = Station.find_by(user_id: current_user.id)
if params.has_key?(:sname)
@supplier = ServiceMap.where("sname LIKE ? and station_id = ?" , "%#{params[:sname]}%", @station.id)
render json:@supplier
elsif params.has_key?(:rname)
@supplier = ServiceMap.where("rname LIKE ? and station_id = ?" , "%#{params[:rname]}%", @station.id)
render json:@supplier
end
else
redirect_to root_path
end
end
end
end
|
class Api::V1::TagTaggablesController < Api::V1::ApiController
before_action :set_tag_taggable, only: %i[show update destroy]
def index
@tag_taggables = current_user.tag_taggables
end
def batch_ensure_tags
params['taggables'].values.each do |taggable_params|
params['tags_ids'].each do |tag_id|
TagTaggable.where(tag_id: tag_id,
taggable_id: taggable_params['id'],
taggable_type: taggable_params['type']).first_or_create
end
end
end
def show
end
def update
if @tag_taggable.update(tag_taggable_params)
render 'show', status: :ok
else
render 'show', status: :unprocessable_entuty
end
end
def create
@tag_taggable = current_user.tag_taggables.new tag_taggable_params
if @tag_taggable.save
render 'show', status: :created
else
render 'show', status: :unprocessable_entuty
end
end
def destroy
@tag_taggable.destroy
end
private
def set_tag_taggable
@tag_taggable = current_user.tag_taggables.find(params[:id])
end
def tag_taggable_params
params.require(:tag_taggable).permit(:id, :taggable_id, :tag_id)
end
end
|
# frozen_string_literal: true
# Filters a collection based on the internal members aggregator
class DuplicateFileIterator
include Enumerable
def initialize(collection = [], duplicates: true)
@collection = collection
@duplicates = duplicates
end
def each(&block)
grouped = @collection.group_by(&:aggregator) # How does this class know about the members internals...? coupling...?
if @duplicates
grouped.select { |k, v| v.length > 1 }.each(&block)
else
grouped.select { |k, v| v.length == 1 }.each(&block)
end
end
end
|
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'spec_helper'
describe TwitterCldr::Shared::TerritoriesContainment do
describe '.parents' do
it 'returns the parent territory' do
expect(described_class.parents('RU')).to eq(['151', 'UN'])
end
it 'returns multiple parents' do
expect(described_class.parents('013')).to match_array(%w[003 019 419])
end
it 'returns [] when given a top-level territory' do
expect(described_class.parents('001')).to eq([])
end
it 'raises an exception when given an invalid territory code' do
expect { described_class.parents('FOO') }.to raise_exception(ArgumentError, 'unknown territory code "FOO"')
end
end
describe '.children' do
it 'returns the immediate children of the territory' do
expect(described_class.children('151')).to eq(%w[BG BY CZ HU MD PL RO RU SK SU UA])
end
it 'returns codes with leading zeros' do
expect(described_class.children('009')).to eq(%w[053 054 057 061 QO])
end
it 'returns an empty array when given a bottom-level territory' do
expect(described_class.children('RU')).to eq([])
end
it 'raises an exception when given an invalid territory code' do
expect { described_class.children('FOO') }.to raise_exception(ArgumentError, 'unknown territory code "FOO"')
end
end
describe '.contains?' do
it 'returns true if the first territory (immediately) contains the second one' do
expect(described_class.contains?('151', 'RU')).to eq(true)
end
it 'returns true if the first territory (non-immediately) contains the second one' do
expect(described_class.contains?('419', 'BZ')).to eq(true)
end
it 'returns true if a territory is part of multiple parent territories' do
expect(described_class.contains?('019', '013')).to eq(true)
expect(described_class.contains?('419', '013')).to eq(true)
end
it 'returns true if the first territory is a top-level territory' do
expect(described_class.contains?('001', '145')).to eq(true)
end
it 'returns false if the first territory does not contain the second one' do
expect(described_class.contains?('419', 'RU')).to eq(false)
end
it 'returns false if the second territory is a top-level territory' do
expect(described_class.contains?('419', '001')).to eq(false)
end
it 'returns false if both territories are identical' do
expect(described_class.contains?('RU', 'RU')).to eq(false)
end
it 'raises an exception is the first territory is invalid' do
expect { described_class.contains?('FOO', 'RU') }.to raise_exception(ArgumentError, 'unknown territory code "FOO"')
end
it 'raises an exception is the second territory is invalid' do
expect { described_class.contains?('RU', 'FOO') }.to raise_exception(ArgumentError, 'unknown territory code "FOO"')
end
end
end
|
class Participation < ApplicationRecord
belongs_to :event
belongs_to :participant, class_name: "User"
after_create :new_participant_email
def new_participant_email
ParticipationMailer.new_participant_email(self.participant,self.event).deliver_now
end
end
|
class MeowsGenerator
def initialize
@basic_symbols = [
%w(m M),
%w(e E),
%w(o O),
%w(oo OO),
%w(w W),
['', '!']
]
end
def init_base_state(basic_symbols)
[0]*basic_symbols.size #array of zeros indexes
end
def next
if @current_meow.nil?
@current_meow = init_base_state @basic_symbols #[0, 0, 0, 0, 0] array with indexes from @basic_symbols
else
increase @current_meow
end
get_value_by_state @current_meow
end
def increase(current_meow)
char_index = current_meow.size - 1 #starting from last char
while true
new_index_value = current_meow[char_index] + 1
if @basic_symbols[char_index][new_index_value].nil?
current_meow[char_index] = 0
char_index -= 1
if char_index < 0
raise 'No more combinations available'
end
else
current_meow[char_index] = new_index_value
break
end
end
end
def get_value_by_state(current_meow)
value = ''
current_meow.each_with_index { |inner_index, outer_index| value += @basic_symbols[outer_index][inner_index] }
value
end
end
|
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "strobe-rails-ext"
s.version = "0.0.1"
s.platform = Gem::Platform::RUBY
s.authors = ["Carl Lerche", "José Valim"]
s.email = ["carl@strobecorp.com", "jose.valim@gmail.com"]
s.homepage = "http://rubygems.org/gems/strobe-rails-ext"
s.summary = "Some extensions to rails that we like to use"
s.description = ""
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "strobe-rails-ext"
# This depends on ActiveSupport and ActionPack for us.
s.add_dependency "railties", "< 3.2.0", ">= 3.0.3"
s.files = Dir["lib/**/*.rb"]
s.require_path = 'lib'
# Provide a rails binary so we don't need to depend
# on the rails gem in strobe internal projects.
s.bindir = 'bin'
s.executables = ['rails']
end
|
class Post < ApplicationRecord
belongs_to :user
validate :user_id, presence: true
validates :body, length: {minimum: 0, maximum: 142}
end
|
class SubTasksController < ApplicationController
def create
@task_params = task_params
@task = Task.find(@task_params[:id])
@task_params[:sub_tasks_attributes].each do |st|
st[:category] = @task.category
end
@task.sub_tasks_attributes = @task_params[:sub_tasks_attributes]
if @task.save
redirect_to @task, notice: 'Subtask was successfully created.'
else
redirect_to @task, notice: 'New subtasks are not valid'
end
end
def edit
@st = Task.find(sub_task_params[:id])
@st.update(sub_task_params)
end
def task_params
params.require(:task).permit(:id, :title,:deadline,
category_attributes: :name, sub_tasks_attributes: :title)
end
def sub_task_params
params.require(:sub_task).permit(:id, :done)
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
movie = Movie.create(title: 'Pulp Fiction',
director: 'Quentin Tarantino',
runtime_in_minutes: 189,
description: 'a movie with a lot of stories',
poster_image_url: 'https://www.movieposter.com/posters/archive/main/36/MPW-18039',
release_date: '1990-06-20'
)
user = User.create!(
email: "joe@gmail.com",
password: "test12",
firstname: 'Joe',
lastname: 'Smith'
)
review = movie.reviews.create!(
user_id: user.id,
text: 'I liked this movie a lot',
rating_out_of_ten: 9
) |
module Fog
module Compute
class DigitalOceanV2
class Real
def list_images
request(
:expects => [200],
:method => 'GET',
:path => '/v2/images'
)
end
end
# noinspection RubyStringKeysInHashInspection
class Mock
def list_images
response = Excon::Response.new
response.status = 200
response.body = {
'images' => [
{
'id' => 7555620,
'name' => 'Nifty New Snapshot',
'distribution' => 'Ubuntu',
'slug' => nil,
'public' => false,
'regions' => %w(nyc2 nyc3),
'created_at' => '2014-11-04T22:23:02Z',
'type' => 'snapshot',
'min_disk_size' => 20,
}
],
'links' => {
'pages' => {
'last' => 'https://api.digitalocean.com/v2/images?page=56&per_page=1',
'next' => 'https://api.digitalocean.com/v2/images?page=2&per_page=1'
}
},
'meta' => {
'total' => 56
}
}
response
end
end
end
end
end
|
# encoding: utf-8
module ActiveRecordUtils
VERSION = '0.4.1'
end # module ActiveRecordUtils
|
require_relative './spec_helper'
require_relative '../far_mar'
describe FarMar::Vendor do
it "does this exist" do
FarMar::Vendor.wont_be_nil
end
describe "self.all" do
let(:all_vendors) { FarMar::Vendor.all}
it "creates an array of vendor info" do
all_vendors.must_be_instance_of(Array)
end
it "creates an array of vendor instances" do
classes = all_vendors.map { |vendor| vendor.class }
classes.uniq.must_equal [FarMar::Vendor]
end
end
describe "self.find" do
let(:vendor_ten) {FarMar::Vendor.find(10)}
it "should find instance of vendor given id" do
vendor_ten.name.must_equal("Kertzmann LLC")
end
it "should return nil when it can't find vendor" do
FarMar::Vendor.find(-3).must_be_nil
end
end
describe ".market" do
let(:vendor_five) { FarMar::Vendor.find(5)}
it "should return the market where the vendor sells" do
vendor_five.market.market_id.must_equal(1)
end
end
describe '.products' do
let(:adam) {FarMar::Vendor.find(8)}
let(:adams_products) {adam.products}
it "should return array of products that the vendor sells" do
adams_products.must_be_instance_of Array
end
it "should return array of instances of FarMar::Product" do
classes = adams_products.map { |product| product.class}
classes.uniq.must_equal [FarMar::Product]
end
end
describe '.sales' do
let(:johnny_sales) {FarMar::Vendor.find(6).sales}
it "should return array of sales instances belonging to vendor" do
classes = johnny_sales.map { |sale| sale.class}
classes.uniq.must_equal [FarMar::Sale]
end
end
describe '.revenue' do
let(:mark) {FarMar::Vendor.find(10)}
it "should return sum of all vendor's sales" do
mark.revenue.class.must_equal Fixnum
end
end
describe 'self.by_market' do
let(:market_one_vendors) {FarMar::Vendor.by_market(2)}
it "should array of vendors with the given market_id" do
market_one_vendors.class.must_equal Array
end
it "should return array of vendor instances" do
classes = market_one_vendors.map { |vendor| vendor.class}
classes.uniq.must_equal [FarMar::Vendor]
end
end
# describe "self.most_revenue(n)" do
# it "should provide n vendors with most revenue" do
# FarMar::Vendor.most_revenue(2)[0].class.must_equal FarMar::Vendor
# end
# end
end
|
require 'test_helper'
class UserEquipsControllerTest < ActionDispatch::IntegrationTest
setup do
@user_equip = user_equips(:one)
end
test "should get index" do
get user_equips_url, as: :json
assert_response :success
end
test "should create user_equip" do
assert_difference('UserEquip.count') do
post user_equips_url, params: { user_equip: { equip_id: @user_equip.equip_id, is_equipped: @user_equip.is_equipped, user_id: @user_equip.user_id } }, as: :json
end
assert_response 201
end
test "should show user_equip" do
get user_equip_url(@user_equip), as: :json
assert_response :success
end
test "should update user_equip" do
patch user_equip_url(@user_equip), params: { user_equip: { equip_id: @user_equip.equip_id, is_equipped: @user_equip.is_equipped, user_id: @user_equip.user_id } }, as: :json
assert_response 200
end
test "should destroy user_equip" do
assert_difference('UserEquip.count', -1) do
delete user_equip_url(@user_equip), as: :json
end
assert_response 204
end
end
|
module ThemedTextService
module_function
def user_notify(appointment)
template = appointment.worker.user_notify_template || <<-TEXT
Здравствуйте <ИМЯ>!
В <ДЕНЬ НЕДЕЛИ> <ДАТА НАЧАЛА> Вы записаны к мастеру <ДМАСТЕР> на следующие услуги: <СПИСОК УСЛУГ>.
Продолжительность приема: <ПРОДОЛЖИТЕЛЬНОСТЬ>, стоимость: <СТОИМОСТЬ> руб.
Телефон: <ТЕЛЕФОН МАСТЕРА>
TEXT
{
'ИМЯ' => appointment.firstname,
'ФАМИЛИЯ' => appointment.lastname,
'ДЕНЬ НЕДЕЛИ' => Organization::GENITIVE_WEEK_DAYS[appointment.start.wday],
'ДАТА НАЧАЛА' => Russian.strftime(appointment.start, '%d %B в %H:%M'),
'СПИСОК УСЛУГ' => appointment.services.order(:name).pluck(:name).join(', '),
'СТОИМОСТЬ' => appointment.cost,
'МАСТЕР' => appointment.worker.name,
'ДМАСТЕР' => appointment.worker.dative_case,
'ПРОДОЛЖИТЕЛЬНОСТЬ' => appointment.showing_time.show_time,
'ТЕЛЕФОН МАСТЕРА' => appointment.worker.phone
}.inject(template) do |result, (substring, value)|
result.gsub!("<#{substring}>", value.to_s) || result
end
end
end
|
class Notification < ActiveRecord::Base
belongs_to :user
belongs_to :notifiable, polymorphic: true
validates :user_id, :presence => true
validates :notifiable_id, :presence => true
validates :notifiable_type, :presence => true
validates :title, :presence => true
scope :viewed, -> {where(viewed: true)}
scope :unviewed, -> {where(viewed: false)}
end
|
class FontArsenal < Formula
head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/arsenal"
desc "Arsenal"
homepage "https://fonts.google.com/specimen/Arsenal"
def install
(share/"fonts").install "Arsenal-Bold.ttf"
(share/"fonts").install "Arsenal-BoldItalic.ttf"
(share/"fonts").install "Arsenal-Italic.ttf"
(share/"fonts").install "Arsenal-Regular.ttf"
end
test do
end
end
|
class User < ActiveRecord::Base
has_many :phone_numbers, dependent: :destroy
has_and_belongs_to_many :street_addresses
end
|
class CreateResources < ActiveRecord::Migration
def self.up
create_table :resources do |t|
t.string :name
t.references :category
t.references :sub_category
t.references :vehicle_model_type
t.string :status
t.string :resource_type
t.string :resource_no
t.text :location
t.string :vehicle_model
t.integer :capacity
t.string :description
t.string :brand_model
t.boolean :is_returnable
t.boolean :is_facilty_avail, :default => false
t.integer :created_by
t.boolean :is_active, :default => true
t.boolean :deleted, :default => false
t.timestamps
end
end
def self.down
drop_table :resources
end
end
|
# == Schema Information
#
# Table name: school_groups
#
# id :bigint(8) not null, primary key
# name :string
# identifier :string
# created_at :datetime not null
# updated_at :datetime not null
#
require 'rails_helper'
RSpec.describe SchoolGroup, type: :model do
# === Relations ===
it { should have_many :incidents }
# === Database (Columns) ===
it { should have_db_column :id }
it { should have_db_column :name }
it { should have_db_column :identifier }
# === Validations (Presence) ===
it { should validate_presence_of :name }
it { should validate_presence_of :identifier }
describe ".ordenation_attributes" do
ordenation_attributes = SchoolGroup.ordenation_attributes
it "should return an array" do
expect(ordenation_attributes).to be_an_instance_of(Array)
ordenation_attributes.each do |attribute|
expect(attribute).to be_an_instance_of(Array)
end
end
ordenation_attributes.each do |attribute|
it "should return user attribute #{attribute}" do
expect(SchoolGroup.attribute_names.include?(attribute.last)).to be true
end
end
end
end
|
class CompanyWrapper
attr_accessor :score
def self.wrap_companies(companies)
wrapped_companies = []
companies.each do |company|
wrapped_companies << CompanyWrapper.new(company)
end
return wrapped_companies
end
def initialize company
@company = company
@score = 0
@rated_fields = {}
end
def rate_field(field, rating)
@rated_fields = {} if @rated_fields.nil?
@rated_fields[field] = rating
end
def is_rated field
!@rated_fields.nil? && !@rated_fields[field].nil?
end
def get_rating field
@rated_fields[field] if !@rated_fields.nil?
end
def add_score value
@score = 0 if @score.nil?
@score += value
end
def method_missing(method, *args)
@company.send(method, *args)
end
end |
require 'pry'
require 'rainbow/ext/string' # Gives access to rainbow gem
travelling = "Y"
def line_n
["Times Square", "34th", "28th N", "23rd N", "Union Square", "8th N"]
end
def line_l
["8th", "6th", "Union Square", "3rd", "1st"]
end
def line_6
["Grand Central", "33rd", "28th", "23rd", "Union Square", "Astor Place"]
end
def find_interchange (start_line, end_line)
return start_line & end_line
end
def find_line (station)
if line_6.include?(station)
return line_6(),"6 Line"
elsif line_l.include?(station)
return line_l(),"L Line"
elsif line_n.include?(station)
return line_n(),"N Line"
else
return "",""
end
end
def trim_lines (line, station, interchange, first_part_of_trip)
station_index = line.index(station)
interchange_index = line.index(interchange)
line.reverse! if(station_index > interchange_index) && first_part_of_trip
line.reverse! if(station_index < interchange_index) && !first_part_of_trip
station_index = line.index(station)
interchange_index = line.index(interchange)
new_line = line.slice!(station_index..interchange_index) if first_part_of_trip == true
new_line = line.slice!(interchange_index..station_index) if first_part_of_trip == false
new_line.pop
new_line.shift
return new_line
end
# call the user and ask him to input his stops
def call_user
print "\n\tN-Line: #{line_n.join(", ").color(:indianred).bright}\n"
print "\n\tL-Line: #{line_l.join(", ").color(:indianred).bright}\n"
print "\n\t6-Line: #{line_6.join(", ").color(:indianred).bright}\n"
print "\n\twhich station are you travelling from? "
start = gets.chomp()
print "\n\tWhich station are you traveling to? "
stop = gets.chomp()
return start,stop
end
# Find the interchange where the lines meet,
# send the lines to the trimmed before and beyond the required stops
# Counts how many stop left in the on the lines.
def interchange_and_stops(start_line,start,end_line,stop)
interchange = find_interchange(start_line,end_line)[0]
start_line = trim_lines(start_line, start, interchange, true) # check directions
end_line = trim_lines(end_line, stop, interchange, false) # for both lines
total_stops = start_line.length + end_line.length + 1
return interchange, start_line, end_line, total_stops
end
# an
def single_line_trip(start_line,start,stop)
start_index = start_line.index(start)
stop_index = start_line.index(stop)
start_line.reverse! if(start_index > stop_index)
start_index = start_line.index(start)
stop_index = start_line.index(stop)
line = start_line.slice!((start_index+1)..(stop_index-1))
return line
end
while (travelling == 'Y')
start, stop = call_user
start_line,name_start_line = find_line(start)
end_line,name_end_line = find_line(stop)
if name_start_line == "" || name_end_line == ""
puts "\n\tInvalid Station".color(:red)
elsif start == stop
puts "\n\tYou're an idiot".color(:red)
elsif name_start_line != name_end_line && start != "Union Square"
interchange, start_line, end_line, total_stops = interchange_and_stops(start_line,start,end_line,stop)
puts "\n \t You are traveling from #{start.color(:green)} on the #{name_start_line.color(:green)}, \n
continue through #{Rainbow(start_line.join(", ")).underline} and change trains to #{name_end_line.color(:green)} at: #{interchange.color(:orange)}. \n
continue your journey through #{Rainbow(end_line.join(", ")).underline} all the way to #{stop.color(:green)}. \n
You have #{total_stops} stop(s) on your journey, good luck.\n"
else
start_line = end_line if start == "Union Square"
line = single_line_trip(start_line,start,stop)
puts "\n \t You are traveling on line #{name_start_line.color(:green)} from #{start.color(:green)}. \n
contine through #{Rainbow(line.join(", ")).underline} all the way to #{stop.color(:green)}.\n
You have #{line.length} stops on your way, good luck!\n"
end
print "Would you like to plan another trip? Y/N "
travelling = gets.chomp()
end
|
require 'sinatra'
require 'sinatra/reloader' if development?
enable :sessions
helpers do
def store_guess(filename, string) # stores the guess in a file
string.downcase!
File.open(filename, "a+") do |file|
file.puts(string)
end
end
def read_guesses # gets the guesses back out of a file and sets them to an array
return [] unless File.exist?("guesses.txt")
return guess_array=File.read("guesses.txt").split("\n")
end
def set_play_word # picks a word from the file
array = []
File.foreach('word_list') do |x|
chomped = x.chomp
array << chomped if (chomped.length == 7)
end
the_word = array.sample.downcase
return the_word
end
def set_blanks_array # creates an array of blanks
blanks_array=[]
session[:play_word].length.times {blanks_array<<"_"}
return blanks_array
end
def blanks_array
session[:blanks_array]
end
def blanks_string # formats the blanks array as a string
return blanks_string= session[:blanks_array].join("")
end
def blanks_string_spaces
return blanks_string_spaces= session[:blanks_array].join(" ")
end# adds spaces to the blanks string so that it looks better
def guess_array
session[:guess_array]
end
def check_guess
session[:play_word].each_char.with_index do |letter, num|
if letter == params["guess"]
session[:blanks_array][num]=params["guess"]
end
end
if !session[:play_word].include? params["guess"]
session[:bad_guess]+=1
end
session[:blanks_string]= blanks_string
session[:blanks_string_spaces] = blanks_string_spaces
end
def win # if win or lose page gets redirected
if session[:bad_guess] < 10 && session[:play_word] == session[:blanks_string]
File.open('guesses.txt', 'w') {|file| file.truncate(0) }
redirect "/win"
elsif session[:bad_guess] == 10
File.open('guesses.txt', 'w') {|file| file.truncate(0) }
redirect "/lose"
end
end
def start_game # triggers methods and sets results as values in sessions hash
File.open('guesses.txt', 'w') {|file| file.truncate(0) }
session[:play_word] = set_play_word
session[:blanks_array] = set_blanks_array
session[:blanks_string] = blanks_string
session[:blanks_string_spaces] = blanks_string_spaces
session[:guess_array]= read_guesses
session[:bad_guess]=0
end
end
get '/' do # welcome page
start_game # calls starts game method once per session
erb :index, layout: :main # shos the main layout which yeilds to index
end
get '/play' do # stat game button takes us here. gets is only to show current state
@play_word=session[:play_word] # sets session values to instance variables so they can be passed to the erb files
@guess= params["guess"]
@guess_array= session[:guess_array]= read_guesses
@blanks_array= session[:blanks_array]
@blanks_string= session[:blanks_string]
@blanks_string_spaces= session[:blanks_string_spaces]
@bad_guess=session[:bad_guess]
erb :play, layout: :main
end
post "/" do # clicking guess will post the new guess save it, check it and check for a win
@guess= params["guess"]
store_guess("guesses.txt", @guess)
check_guess
win
redirect "/play"
end
get '/win' do
@play_word=session[:play_word]
erb :win, layout: :main # shos the winning page
end
get '/lose' do
@play_word=session[:play_word]
erb :lose, layout: :main # shows the losing page
end
|
class CreateAddresses < ActiveRecord::Migration
def change
create_table :addresses do |t|
t.boolean :correct, default: false
t.string :country_code
t.string :city
t.string :address_1
t.string :address_2
t.string :address_3
t.string :postcode
t.string :county
t.boolean :t_purchase_order
t.boolean :t_invoice
t.boolean :t_release_note
t.boolean :t_quality
t.boolean :t_credit_note
t.boolean :t_debit_note
t.boolean :t_delivery_address
# audit
t.boolean :dormant, default: false
t.boolean :record_exists, default: true
t.integer :record_last_change_by
t.integer :record_created_by
t.timestamps null: false
# references
t.references :company, index: true, foreign_key: true
end
end
end
|
# frozen_string_literal: true
require "spec_helper"
RSpec.describe Tikkie::Api::V1::AccessToken do
describe '#token' do
it 'returns the access token' do
token = Tikkie::Api::V1::AccessToken.new("12345", 0)
expect(token.token).to eq("12345")
end
end
describe '#expired?' do
it 'is not expired when less than 300 seconds have passed' do
token = Tikkie::Api::V1::AccessToken.new("12345", 300)
Timecop.freeze(Time.now + 180) do
expect(token.expired?).to be false
end
end
it 'is not expired when more than 300 seconds have passed' do
token = Tikkie::Api::V1::AccessToken.new("12345", 300)
Timecop.freeze(Time.now + 300) do
expect(token.expired?).to be true
end
end
end
end
|
class UsersController < ApplicationController
require 'happybirthday'
def index
@events = current_user.events.order(:department_id)
birthday = Happybirthday.born_on(current_user.birthday)
@birthday = birthday.age.years_old
end
def show
@user = User.find(params[:id])
@events = @user.events.order(:department_id)
birthday = Happybirthday.born_on(@user.birthday)
@birthday = birthday.age.years_old
end
def edit
end
def update
if current_user.update(user_params)
redirect_to root_path
else
render :edit
end
end
private
def user_params
params.require(:user).permit(:nickname, :email, :duty_station)
end
end
|
require "rails_helper"
RSpec.describe Api::V1::InvoiceItems::InvoicesController, type: :controller do
describe "GET #show.json" do
let(:json_response) { JSON.parse(response.body) }
let(:invoice_item) { create(:invoice_item) }
let(:invoice) { invoice_item.invoice }
it "responds with successful 200 HTTP status code" do
get :show, invoice_item_id: invoice_item.id, format: :json
expect(response).to be_success
expect(response).to have_http_status(200)
end
it "returns the info for the invoice item's invoice in JSON format" do
get :show, invoice_item_id: invoice_item.id, format: :json
expect(json_response["id"]).to eq(invoice.id)
expect(json_response["customer_id"]).to eq(invoice.customer_id)
expect(json_response["merchant_id"]).to eq(invoice.merchant_id)
expect(json_response["status"]).to eq(invoice.status)
expect(json_response["updated_at"].to_json).to eq(invoice.updated_at.to_json)
expect(json_response["created_at"].to_json).to eq(invoice.created_at.to_json)
end
end
end
|
# Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
include AuthenticatedSystem
before_filter :login_from_cookie
def current_playlist
return unless logged_in?
current_user.playlist ||= Playlist.new(:name => 'default')
end
end
|
class User < ActiveRecord::Base
has_many :boards, -> { order(:title) }, dependent: :destroy
has_and_belongs_to_many :subscriptions, class_name: "Board", join_table: "subscriptions"
# Include default devise modules. Others available are:
# :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable, :timeoutable
validates :first_name, :last_name, presence: true
# @return [Boolean] true if user is admin or rudy.rigot@gmail.com
def admin?
admin || email == 'rudy.rigot@gmail.com'
end
def full_name
if first_name.present? && last_name.present?
"#{first_name} #{last_name}"
else
email
end
end
# @return [String] a random password of size 10
def self.random_password
Array.new(10).map { (65 + rand(58)).chr }.join
end
end
|
require 'spec_helper'
require 'rack/mock'
describe "Rack::Molasses" do
def mock_request(options={})
app = lambda {|env| [200, {"Content-Type" => "text/plain"}, ["Hello World"]]}
app = Rack::Molasses.new(app, options)
Rack::MockRequest.new(app)
end
def mock_request_with_cache_control(cache_control, options={})
headers = {"Content-Type" => "text/plain", 'Cache-Control' => cache_control}
app = lambda {|env| [200, headers, ["Hello World"]]}
app = Rack::Molasses.new(app, options)
Rack::MockRequest.new(app)
end
DEFAULT_MAX_AGE = TestHelp::ONE_HOUR
let(:cacheable_response) {
mock_request(:cache_when_path_matches => /images/).get('/images/foo')
}
let(:uncacheable_response) {
mock_request(:cache_when_path_matches => /images/).get('/some/path')
}
context 'side-effects' do
specify 'should not change response body' do
uncacheable_response.body.should == 'Hello World'
cacheable_response.body.should == 'Hello World'
end
specify 'should not change response status' do
uncacheable_response.status == 200
cacheable_response.status == 200
end
specify 'should not change other headers' do
uncacheable_response.headers['Content-Type'].should == 'text/plain'
cacheable_response.headers['Content-Type'].should == 'text/plain'
end
end
context 'default behavior' do
specify 'should only cache get requests' do
request = mock_request(:cache_when_path_matches => /images/)
response = request.get('/images/foo')
response.should be_cached
response = request.post('/images/foo')
response.should_not be_cached
response = request.put('/images/foo')
response.should_not be_cached
response = request.delete('/images/foo')
response.should_not be_cached
end
specify 'should set cache control to public when caching' do
cacheable_response.should have_cache_control_public
end
specify 'should set max-age to one hour by default when caching' do
cacheable_response.should have_max_age(TestHelp::ONE_HOUR)
end
specify 'should raise error if cache_when_path_matches is absent' do
lambda { mock_request }.should raise_error(Rack::Molasses::Error)
end
end
context 'path matching' do
specify 'should cache when path matches regex' do
request = mock_request(:cache_when_path_matches => /images/)
response = request.get('/images/foo')
response.should be_cached
response = request.get('/image/foo')
response.should_not be_cached
request = mock_request(:cache_when_path_matches => /fred\-/)
response = request.get('/alfred-the-butler')
response.should be_cached
response = request.get('/alf-the-butler')
response.should_not be_cached
end
specify 'should cache when path starts with string' do
request = mock_request(:cache_when_path_matches => '/images')
response = request.get('/images/foo')
response.should be_cached
response = request.get('/image/foo')
response.should_not be_cached
request = mock_request(:cache_when_path_matches => 'fred')
response = request.get('/alfred-the-butler')
response.should_not be_cached
response = request.get('/alf-the-butler')
response.should_not be_cached
end
specify 'should cache when path matches one of the regexen' do
request = mock_request(:cache_when_path_matches => [/images/, /stylesheets/])
response = request.get('/images/foo')
response.should be_cached
response = request.get('/image/foo')
response.should_not be_cached
response = request.get('/bar/stylesheets/foo')
response.should be_cached
response = request.get('/bar/style/sheets/foo')
response.should_not be_cached
end
specify 'should cache when path starts with one of the strings' do
request = mock_request(:cache_when_path_matches => ['/foo', '/bar', '/baz'])
response = request.get('/foo/images/fo.png')
response.should be_cached
response = request.get('/images/march')
response.should_not be_cached
response = request.get('/bar/stylesheets')
response.should be_cached
response = request.get('/baz')
response.should be_cached
end
specify 'should cache when path matches one of the strings or regexen' do
request = mock_request(:cache_when_path_matches => [/foo/, '/bar', 'baz'])
response = request.get('/images/foo')
response.should be_cached
response = request.get('/images/march')
response.should_not be_cached
response = request.get('/bar/none')
response.should be_cached
end
specify 'should raise an error if cache_when_path_matches is neither an array, string nor regex' do
lambda do
request = mock_request(:cache_when_path_matches => 7)
response = request.get('/images/foo')
end.should raise_error(Rack::Molasses::Error)
end
end
context 'cache busters' do
specify 'should recognize a date-based query string cache buster (Rails < 3.1)' do
request = mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '30 seconds')
response = request.get('/images/foo.png')
response.should have_max_age(DEFAULT_MAX_AGE)
response = request.get('/images/foo.png?6734897846')
response.should have_max_age(30)
end
specify 'should recognize a file fingerprint cache buster (Rails 3.1+)' do
request = mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '30 seconds')
response = request.get('/images/foo.png')
response.should have_max_age(DEFAULT_MAX_AGE)
response = request.get('/images/foo-2ba81a47c5512d9e23c435c1f29373cb.png')
response.should have_max_age(30)
response = request.get('/images/foo-e19343e6c6c76f8f634a685eba7c0880648b1389.png')
response.should have_max_age(30)
end
specify 'should not be tricked by things that look like cache busters' do
request = mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '30 seconds')
response = request.get('/images/foo.png?value=3487986534')
response.should have_max_age(DEFAULT_MAX_AGE)
response = request.get('/images/foo.png?2012')
response.should have_max_age(DEFAULT_MAX_AGE)
response = request.get('/images/foo-12302012.png')
response.should have_max_age(DEFAULT_MAX_AGE)
response = request.get('/images/foo-barbaz.png')
response.should have_max_age(DEFAULT_MAX_AGE)
end
specify 'should use :when_cache_busters_absent_cache_for as default max-age value' do
request = mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_absent_cache_for => '15 seconds')
response = request.get('/images/foo.png')
response.should have_max_age(15)
response = request.get('/images/foo.png?1756489253')
response.should have_max_age(15)
end
specify 'should be able to set different max-age values depending on whether cache busters are present' do
request = mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '45 seconds',
:when_cache_busters_absent_cache_for => '15 seconds')
response = request.get('/images/foo.png')
response.should have_max_age(15)
response = request.get('/images/foo.png?7845893467')
response.should have_max_age(45)
response = request.get('/images/foo-2ba81a47c5512d9e23c435c1f29373cb.png')
response.should have_max_age(45)
end
specify 'should be able to set cache time in minutes' do
request = mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '45 minutes',
:when_cache_busters_absent_cache_for => '15 minutes')
response = request.get('/images/foo.png')
response.should have_max_age(15 * TestHelp::ONE_MINUTE)
response = request.get('/images/foo.png?7845893467')
response.should have_max_age(45 * TestHelp::ONE_MINUTE)
end
specify 'should be able to set cache time in hours' do
request = mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '45 hours',
:when_cache_busters_absent_cache_for => '15 hours')
response = request.get('/images/foo.png')
response.should have_max_age(15 * TestHelp::ONE_HOUR)
response = request.get('/images/foo.png?7845893467')
response.should have_max_age(45 * TestHelp::ONE_HOUR)
end
specify 'should be able to set cache time in days' do
request = mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '45 days',
:when_cache_busters_absent_cache_for => '15 days')
response = request.get('/images/foo.png')
response.should have_max_age(15 * TestHelp::ONE_DAY)
response = request.get('/images/foo.png?7845893467')
response.should have_max_age(45 * TestHelp::ONE_DAY)
end
specify 'should be able to set cache time in weeks' do
request = mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '45 weeks',
:when_cache_busters_absent_cache_for => '15 weeks')
response = request.get('/images/foo.png')
response.should have_max_age(15 * TestHelp::ONE_WEEK)
response = request.get('/images/foo.png?7845893467')
response.should have_max_age(45 * TestHelp::ONE_WEEK)
end
specify 'should be able to set cache time in months' do
request = mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '4 months',
:when_cache_busters_absent_cache_for => '2 months')
response = request.get('/images/foo.png')
response.should have_max_age(2 * TestHelp::ONE_MONTH)
response = request.get('/images/foo.png?7845893467')
response.should have_max_age(4 * TestHelp::ONE_MONTH)
end
specify 'should be able to set cache time in years' do
request = mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '1 year',
:when_cache_busters_absent_cache_for => '1 year')
response = request.get('/images/foo.png')
response.should have_max_age(TestHelp::ONE_YEAR)
response = request.get('/images/foo.png?7845893467')
response.should have_max_age(TestHelp::ONE_YEAR)
end
specify 'should not be able to set cache time longer than a year' do
lambda do
mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '2 years',
:when_cache_busters_absent_cache_for => '1 month')
end.should raise_error(Rack::Molasses::Error)
lambda do
mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '2 days',
:when_cache_busters_absent_cache_for => '13 months')
end.should raise_error(Rack::Molasses::Error)
end
specify 'should not be able to set a negative cache time' do
lambda do
mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_present_cache_for => '-4 days',
:when_cache_busters_absent_cache_for => '1 month')
end.should raise_error(Rack::Molasses::Error)
end
specify 'should be able to set a cache time to zero' do
request = mock_request(:cache_when_path_matches => '/images',
:when_cache_busters_absent_cache_for => '0 seconds')
response = request.get('/images/foo.png')
response.should have_max_age(0)
end
end
context 'existing cache control settings' do
specify 'should not change any cache-control values if private is already set' do
request = mock_request_with_cache_control('private', :cache_when_path_matches => '/images')
response = request.get('/images/foo.png')
response.headers['Cache-Control'].should == 'private'
request = mock_request_with_cache_control('private, max-age=400, must-revalidate', :cache_when_path_matches => '/images')
response = request.get('/images/foo.png')
response.headers['Cache-Control'].should == 'private, max-age=400, must-revalidate'
end
specify 'should not change any cache-control values if no-store is already set' do
request = mock_request_with_cache_control('no-store', :cache_when_path_matches => '/images')
response = request.get('/images/foo.png')
response.headers['Cache-Control'].should == 'no-store'
end
specify 'should not change any cache-control values if max-age is already set' do
request = mock_request_with_cache_control('max-age=4500', :cache_when_path_matches => '/images')
response = request.get('/images/foo.png')
response.headers['Cache-Control'].should == 'max-age=4500'
request = mock_request_with_cache_control('max-age=400, must-revalidate', :cache_when_path_matches => '/images')
response = request.get('/images/foo.png')
response.headers['Cache-Control'].should == 'max-age=400, must-revalidate'
end
end
end
|
class TodoItem < ApplicationRecord
belongs_to :todo_list
PRIORITIES = [
['Later', 1],
['Next', 2],
['Now', 3]
]
def completed?
!completed_at.blank?
end
end
|
class CalculatorsController < ApplicationController
def new
@calculator = Calculator.new
end
def index
@calculators = Calculator.all
end
def create
@calculator = Calculator.new(calculator_params)
if @calculator.save
flash[:notice] = "Your estimate was calculated."
redirect_to calculator_path(@calculator)
else
flash.now[:alert] = "There was an error saving the calculator. Please try again."
render :new
end
end
def edit
end
def update
end
def show
@calculator = Calculator.find(params[:id])
end
def delete
end
private
def calculator_params
params.require(:calculator).permit(:six_hundred, :eight_hundred, :discount_code, :photo_package)
end
end
|
class User < ActiveRecord::Base
has_many :keys
validates_presence_of :email , :on => :create
validates :email, presence: true
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/
validates_uniqueness_of :current_token
# raise
before_create :create_api_token
validates :email, length: { maximum: 25 }
private
def create_api_token
self.current_token = create_token
self.token_counts =+ 1 # unless self.token_counts < 5
end
def create_token
SecureRandom.hex
end
end
|
require "./lib/interface/message.rb"
module Hoze
class TestMessage < Message
attr_reader :delay_received, :ack_received, :reject_received
def initialize payload,timestamp,metadata
@payload = payload
@timestamp = timestamp
@metadata = metadata
@delay_received = []
@ack_received = []
@reject_received = []
end
# Ask for more time before acknowledging
def delay! seconds
@delay_received << seconds
end
# Acknowledge the message
def ack!
@ack_received << "ack"
end
# Release the message
def reject!
@reject_received << "reject"
end
end
end |
class Kitsu::Anime
require 'open-uri'
BASE_URL = 'anime?filter[seasonYear]='.freeze
def scrap_anime
(2017..Date.current.year).each do |year|
@titles ||= anime(year)
raise StandardError.new(@titles.body['errors']) if @titles.body['errors'].present?
create_or_update_anime(@titles)
end
end
def anime(year)
@response ||= api.get("#{BASE_URL}#{year}")
end
private
def api
Kitsu::Client.connect
end
def create_or_update_anime(titles)
create_or_update(titles)
sleep 0.5
new_page = api.get(titles.body['links']['next'])
create_or_update_anime(new_page) if new_page.body['links']['next'].present?
end
def create_or_update(titles)
titles.body['data'].each_with_index do |title, index|
next if title['attributes']['subtype'] == 'music'
params = parsed_anime_params(title['attributes'], title['id'])
anime = Anime.find_or_create_by(kitsu_id: params[:kitsu_id])
anime.update(params)
break if index >= 10
end
end
def parsed_anime_params(title, id)
{
description: title['synopsis'],
eng_title: title['titles']['en'],
romaji_title: title['titles']['en_jp'],
kanji_title: title['titles']['ja_jp'],
alternative_titles: title['abbreviatedTitles'],
aired_from: title['startDate'],
aired_to: title['endDate'],
type: title['subtype'],
status: title['status'],
episode_count: title['episodeCount'],
episode_length: title['episodeLength'],
remote_poster_url: title['posterImage']['original'],
kitsu_id: id.to_i
}
end
end
|
class BookingsController < ApplicationController
before_action :find_studio, only: [ :new, :create]
def index
@bookings = Booking.all
@bookings = policy_scope(Booking)
@bookings = policy_scope(Booking).order(created_at: :desc)
end
def new
@booking = Booking.new
end
def create
@booking = Booking.new(booking_params)
@booking.studio = @studio
authorize @booking.studio
@booking.user = current_user
@booking.total_price = @studio.rate * total_hours
if @booking.save
redirect_to studio_path(@studio), notice: 'Your booking has been saved!'
else
redirect_to studio_path(@studio), notice: 'Please try again!'
end
end
def destroy
@booking = Booking.find(params[:id])
@booking.destroy!
redirect_to studio_path(@booking.studio), notice: 'Your booking has been deleted!'
authorize @booking
end
private
def booking_params
params.require(:booking).permit(:end_date, :start_date)
end
def find_studio
@studio = Studio.find(params[:studio_id])
end
def total_hours
((@booking.end_date - @booking.start_date) / 3600).to_i
end
end
|
class PaymentsController < ApplicationController
before_action :set_payment, only: [:show, :edit, :update]
before_action :set_subscription
before_action :set_plan, only: [:create, :update]
before_action :check_last_pending, only: :new
def index
end
def show
end
def new
@payment = Payment.new
end
def create
subscription =
if @subscription && !@subscription.expired?
@subscription
else
Subscription.not_expired.find_or_create_by(
user: current_user,
package: @plan.package
)
end
payment = subscription.payments.create payment_params.merge(
user: current_user,
status: :pending
)
payment.make_charge params[:stripeToken]
flash[:notice] = t ".payment_success"
redirect_to account_path
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_account_payment_path
end
def edit
end
def update
@payment.update payment_params
@payment.make_charge params[:stripeToken]
flash[:notice] = t ".payment_success"
redirect_to account_path
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_account_payment_path
end
private
def set_payment
@payment = Payment.find_by id: params[:id]
return if @payment.present?
flash[:notice] = t "payments.payment_not_found"
redirect_to account_path
end
def payment_params
params.require(:payment).permit :plan_id
end
def set_subscription
return if params[:subscription_id].blank?
@subscription = Subscription.find_by id: params[:subscription_id]
return if @subscription.present?
flash[:notice] = t "payments.subscription_not_found"
redirect_to account_path
end
def set_plan
@plan = Plan.find_by id: params[:payment][:plan_id]
return if @plan.present?
flash[:notice] = t "payments.plan_not_found"
redirect_to account_path
end
def check_last_pending
return unless (subscription = set_subscription) &&
subscription.payment_pending?
flash[:notice] = t ".redirect_last_pending_payment"
redirect_to edit_account_subscription_payment_path(
subscription, subscription.payments.pending.last
)
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def current_user
User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
def current_user_admin?
current_user && current_user.admin?
end
helper_method :current_user_admin?
def require_login
unless current_user
redirect_to new_session_url, alert: "Bitte erst einloggen!"
end
end
def require_admin
unless current_user_admin?
redirect_to root_path, alert: "Na, schon mal etwas von Hierarchie gehört, du bist kein Admin!!!"
end
end
end
|
class TcTemplatesController < ApplicationController
before_filter :login_required
before_filter :template_presence_required, :only=>"settings"
before_filter :general_settings_required, :only=>"settings"
before_filter :find_template
filter_access_to :all
include TcTemplateGenerateCertificatesHelper
def settings
@header, @footer, @student_details = TcTemplateField.get_template_settings(@current_template)
@student_details_ids=@current_template.tc_template_field_student_details_main_field_ids
@config_date_format,@config_date_separator = get_date_format
end
def current_tc_preview
@tc_data = @current_template.get_current_preview_settings
render :pdf => 'transfer_certificate_preview_pdf',
:header => {:html => nil},
:footer => {:html => nil},
:margin=> {:top=> 10, :bottom=> 10, :left=> 10, :right=> 10},
:zoom => 1,:layout => "tc_pdf.html",
:show_as_html=> params[:d].present?
end
private
def get_date_format
date_format = Configuration.find_by_config_key('DateFormat').config_value
date_separator = Configuration.find_by_config_key('DateFormatSeparator').config_value
return date_format,date_separator
end
def template_presence_required
unless TcTemplateVersion.current
TcTemplateVersion.initialize_first_template
TcTemplateVersion.initialize_sub_fields
end
end
def general_settings_required
unless Configuration.find_by_config_key('DateFormat')
flash[:notice] = "#{t('no_general_settings_found')}"
redirect_to :controller=>"tc_templates", :action=>"index"
end
end
def find_template
@current_template = TcTemplateVersion.current
end
end
|
module Typeable
public
def validType
raise "Not implemented"
end
end
class Parser
include Typeable
private
@config = nil
@argument = nil
public
def initialize config = Config.new
@config = config
end
def parse input = ""
arg = input.split
@argument = Argument.new input
@argument.set_command arg[0]
@argument.set_parameters arg.drop(1)
end
def get_argument
@argument
end
def get_result
res = ""
if @argument.get_command == "konversi" || @argument.get_command == "ubah"
converter = Converter.new @argument
res = converter.get_result
else
res = "Aku belum belajar buat ini..."
end
return res
end
def validType
type_a = @argument.get_command.instance_of? String
type_b = @argument.get_original.instance_of? String
type_c = @argument.get_parameters.instance_of? Array
return type_a && type_b && type_c
end
end
|
module Shoperb module Theme module Editor
module Mounter
class Server
class ExceptionHandler
def initialize(app)
@app = app
end
def call(env)
begin
@app.call env
rescue Exception => e
Error.report_rack(e, env)
raise e
end
end
end
end
end
end end end
|
class ModalitiesController < ApplicationController
before_action :authenticate_user!
def index
@modalities = Modality.all
end
def new
@modality = Modality.new
end
def show
@modality = Modality.find(params[:id])
end
def edit
@modality = Modality.find(params[:id])
end
def create
@modality = Modality.new(modality_params)
if @modality.save
redirect_to modalities_path, notice: 'Modalidade artística salva com sucesso!'
else
render action: :new
end
end
def update
@modality = Modality.find(params[:id])
if @modality.update(modality_params)
redirect_to modalities_path, notice: 'Modalidade artística atualizada com sucesso!'
else
render action: :edit
end
end
def destroy
@modality = Modality.find(params[:id])
if @modality.delete
redirect_to modalities_path, notice: 'Modalidade removida com sucesso!'
else
redirect_to modalities_path, alert: 'Erro ao remover modalidade!'
end
end
private
def modality_params
params.require(:modality).permit(:name)
end
end
|
class AddVoiceFieldsToCampaign < ActiveRecord::Migration
def change
add_column :campaigns, :voice_call_script, :text, default: nil
add_column :campaigns, :voice_call_number, :string, default: nil
end
end
|
class ServiceLengthsController < ApplicationController
# GET /service_lengths
# GET /service_lengths.xml
def index
@service_lengths = ServiceLength.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @service_lengths }
end
end
# GET /service_lengths/1
# GET /service_lengths/1.xml
def show
@service_length = ServiceLength.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @service_length }
end
end
# GET /service_lengths/new
# GET /service_lengths/new.xml
def new
@service_length = ServiceLength.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @service_length }
end
end
# GET /service_lengths/1/edit
def edit
@service_length = ServiceLength.find(params[:id])
end
# POST /service_lengths
# POST /service_lengths.xml
def create
@service_length = ServiceLength.new(params[:service_length])
respond_to do |format|
if @service_length.save
flash[:notice] = 'ServiceLength was successfully created.'
format.html { redirect_to(@service_length) }
format.xml { render :xml => @service_length, :status => :created, :location => @service_length }
else
format.html { render :action => "new" }
format.xml { render :xml => @service_length.errors, :status => :unprocessable_entity }
end
end
end
# PUT /service_lengths/1
# PUT /service_lengths/1.xml
def update
@service_length = ServiceLength.find(params[:id])
respond_to do |format|
if @service_length.update_attributes(params[:service_length])
flash[:notice] = 'ServiceLength was successfully updated.'
format.html { redirect_to(@service_length) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @service_length.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /service_lengths/1
# DELETE /service_lengths/1.xml
def destroy
@service_length = ServiceLength.find(params[:id])
@service_length.destroy
respond_to do |format|
format.html { redirect_to(service_lengths_url) }
format.xml { head :ok }
end
end
end
|
# :nodoc:
class Array
# Yields unique and distinct permutations of _self_ to the block.
# This method does NOT require that array elements are Comparable.
# rubocop:disable CyclomaticComplexity, AbcSize, MethodLength, PerceivedComplexity, LineLength
def distinct_permutation
return enum_for(:distinct_permutation) unless block_given?
copy = []
# Store in a hash like `{ object_id => object, ... }` to look-up later.
hash = map.with_object({}) do |obj, mem|
oid = find { |o| o == obj }.object_id # TODO: optimize `find`.
copy << oid
mem.merge!(oid => obj)
end
copy.sort!
yield copy.map { |oid| hash[oid] } # retrieves original objects.
return if length < 2
# rubocop:disable InfiniteLoop, LiteralInCondition
while true # fasterer gem says this is faster than `Kernel#loop`.
# from: "The Art of Computer Programming" by Donald Knuth.
j = length - 2
j -= 1 while 0 < j && copy[j + 1] <= copy[j]
break if copy[j + 1] <= copy[j]
l = length - 1
l -= 1 while copy[l] <= copy[j]
copy[j], copy[l] = copy[l], copy[j]
copy[j + 1..-1] = copy[j + 1..-1].reverse
yield copy.map { |oid| hash[oid] }
end
end
end
|
class RefinerycmsSnippets < Refinery::Generators::EngineInstaller
source_root File.expand_path('../../../', __FILE__)
engine_name "snippets"
end
|
class Shoe
attr_accessor :color, :size, :material, :condition #can we change these attriabutes? The answer should be YES
attr_reader :brand
def initialize(brand) #I have initialized a brand for class Shoe.
@brand = brand
end
def cobble
#@condition = "new"
puts "Your shoe is as good as new!"
self.condition = "new"
end
# def brand #I can access the brand of the shoe <-- not needed it is in the attr_reader
# @brand
# end
end #end of class
|
# https://github.com/muzfuz/CodeLessons/blob/master/binary_search/binary_search.rb
#Constructor for the individual nodes
class Node
# instance variables, value, left & right child
attr_accessor :value, :left_child, :right_child
# looks like each node will have a value & a left & right child (but both children are nil)
def initialize(value, left_child=nil, right_child=nil)
@value = value
@left_child = left_child
@right_child = right_child
end
end
# remember left child is smaller, right is larger
#Constructor for our Binary Tree, includes three search methods
class BinarySearchTree
# instance variables
attr_accessor :array, :tree
# Instance variables begin with @.
def initialize(array, tree=nil)
@array = array
@tree = tree
build_tree(@array)
end
#Sorts the array using the merge_sort method, and builds the tree.
def build_tree(array, left=0, right=array.length-1)
# base case
return if left > right
# from smallest to largest
array = merge_sort(array)
# middle index, make this the first node
index_mid = left + (right-left) / 2
node = Node.new(array[index_mid])
# i think it's making the left node (smaller), & right (larger)
# looks like it is recursion
node.left_child = build_tree(array, left, index_mid-1)
node.right_child = build_tree(array, index_mid+1, right)
@tree = node
@tree
end
=begin
http://en.wikipedia.org/wiki/Breadth-first_search#Algorithm
The algorithm uses a queue data structure to store intermediate results as it traverses the graph, as follows:
1 Enqueue the root node
2 Dequeue a node and examine it
If the element sought is found in this node, quit the search and return a result.
Otherwise enqueue any successors (the direct child nodes) that have not yet been discovered.
3 If the queue is empty, every node on the graph has been examined – quit the search and return "not found".
4 If the queue is not empty, repeat from Step 2.
=end
#ITERATIVE BREADTH FIRST SEARCH method
def breadth_first_search(query)
# empty array
queue = []
root = @tree.value
return @tree if root == query #Returns the root item if the query matches
left_child = @tree.left_child
right_child = @tree.right_child
# i think if the target is smaller, add the left child
queue << left_child if left_child != nil
queue << right_child if right_child != nil
loop do
# if nothing in queue, return nil
return nil if queue.empty?
# Removes the first element of self and returns it (shifting all other elements down by one). Returns nil if the array is empty.
node = queue.shift
return node if query == node.value
# i think it continues the search, left if target is smaller, right if target is larger
# also continues unless there is no child
queue << node.left_child if node.left_child != nil
queue << node.right_child if node.right_child != nil
end
end
=begin
https://www.youtube.com/watch?v=iaBEKo5sM7w
This is one of the important Graph traversal technique. DFS is based on stack data structure.
=end
#ITERATIVE DEPTH FIRST SEARCH METHOD
def depth_first_search(query)
stack = [@tree]
loop do
# exit when empty stack
return nil if stack.empty?
# node is equal to top of stack
node = stack.pop
# return node if match
return node if query == node.value
# i think it is pushing every descendant of the parent?
stack.push node.left_child if node.left_child != nil
stack.push node.right_child if node.right_child != nil
end
end
#RECURSIVE DEPTH FIRST SEARCH METHOD
def dfs_recursive(query, node=@tree)
return nil if node.nil?
return node if query == node.value
# left search equals if the left child is not nil then call the method with target & left child node parameters, otherwise is nil
left_search = node.left_child != nil ? dfs_recursive(query, node.left_child) : nil
# return if left search does not result in nil
return left_search if left_search != nil
right_search = node.right_child != nil ? dfs_recursive(query, node.right_child) : nil
return right_search if right_search != nil
end
#MERGE SORT METHOD - Used for pre-sorting the array!
def merge_sort(array)
len = array.length
return array if len == 1 #Base case set to an array size of 1
array1 = array[0..(len/2)-1] #Split the array in half
array2 = array[len/2..-1] #Array two gets the longer half if it's an odd length
a1 = merge_sort(array1) #Split array1 in half again recursively
a2 = merge_sort(array2) #Split array2 in half again recursively
merge(a1, a2) #Call the merge function on the split arrays
end
#Helper method for Merge Sort
def merge(array1, array2, merged_array=[])
len_of_a1 = array1.length #Get length of arrays and compare to the array's index
len_of_a2 = array2.length
index1 = 0 #Set the starting index for both arrays - always 0 since we are going left to right.
index2 = 0
while index1 < len_of_a1 and index2 < len_of_a2 #This loop continues until the end of one of the arrays is reached
if array1[index1] < array2[index2] #It compares the index values of both arrays, and appends the one that is lower in value
merged_array << array1[index1]
index1 += 1
else
merged_array << array2[index2]
index2 += 1
end
end
if index1 < len_of_a1 #Appends any remaining values to the merged array
merged_array += array1[index1..-1]
elsif index2 < len_of_a2
merged_array += array2[index2..-1]
end
merged_array #Returns the merged array
end
#Use this function for debugging / displaying the tree.
def display_tree()
list = []
yield @tree.value
left_child = @tree.left_child
right_child = @tree.right_child
list << left_child if left_child != nil
list << right_child if right_child != nil
loop do
break if list.empty?
node = list.shift
yield node.value
list << node.left_child if node.left_child != nil
list << node.right_child if node.right_child != nil
end
end
end
###########
# TEST CODE
test_array = [1, 7, 4, 23, 8, 9, 4, 3, 5, 7, 9, 67, 6345, 324]
test_array2 = [9,8,7,6,5,4,3,2,1,0]
test_array3 = ['a', 'c', 'd', 'u', 'n', 'z', 'uganda', 'cow']
#Assign instance of class
tree = BinarySearchTree.new(test_array)
#Use the display_tree function for debug purposes
tree.display_tree {|x| print "#{x} "}
print "\n"
#These should all return the appropriate 'Node' object
p tree.breadth_first_search(23)
p tree.depth_first_search(23)
p tree.dfs_recursive(23)
|
require 'spec_helper'
describe "Viewing list of reviews" do
it "shows the reviews for a specified facility" do
facility1 = Facility.create!(facility_attributes(name: "CareFully"))
review1 = facility1.reviews.create!(review_attributes(name: "Ali S"))
review2 = facility1.reviews.create!(review_attributes(name: "J T"))
facility2 = Facility.create!(facility_attributes(name: "Full Care"))
review3 = facility2.reviews.create!(review_attributes(name: "P T"))
visit facility_reviews_path(facility1)
expect(page).to have_text(review1.name)
expect(page).to have_text(review2.name)
expect(page).not_to have_text(review3.name)
end
end
|
# pseudo
# Swapping the first and last name
# - first split up the full name into first and last name
# - then move that first name ahead of the last name
# - then unsplitting it by joining it back together
# Changing all of the vowels (a, e, i, o, or u) to the next vowel in 'aeiou',
#and all of the consonants (everything else besides the vowels)
# to the next consonant in the alphabet.
# So 'a' would become 'e', 'u' would become 'a', and 'd' would become 'f'.
# - take all of lowercase and uppercase vowels and consonants to make a crosswalk
# - move them each up one character (closer to z)
# -if that moveup in character takes them out of case, then start back at start a
# - use keys to match with reversed name in vowels
# - substitute over time that key with its value
# - output the vowel substitution
# - use keys to match with reversed name in consonants
# - substitute over time that key with its value
# - output the vowel and consonant substitution
#####################
# alias maker-storer
# declare empty full_name variable for method
full_name = ""
# declare alias maker method with full_name as variable
def alias_maker(full_name)
# declare empty print database variable
quit = false
# declare empty name hash for iterating through with merge
# will print if quit is true
name_hash = {}
# until the user wants to quit and print database
# separated quit from full_name so no chance of running input of quit
until quit == true
# user interface with instructions for quit as well
# current system setup for one first and one last name
puts "Enter a first and a last name to get an alias:"
puts "(type quit to exit and print that alias)"
# starting off with alias input so quit doesn't become full_name key
alias_input = gets.chomp
# setup if/then for looping through all the names
# will set quit boolean to true
if alias_input == "quit"
quit = true
# test code
# prints the final hash
name_hash.each { |full_name,alias_name|
puts "#{full_name} is an operative also known as #{alias_name}."
}
else
# alias input becomes full_name
full_name = alias_input
end
# divide full name based on its space
# thus need one first and one last
first_last = full_name.split
# bring back one first and one last in last-first order
last_first = first_last[1] + " " + first_last[0]
# set hash for all vowels in caps and lower for rotate one forward (toward z)
# this way to iterate using gsub quicker
# end of vowel list starts back at beginning for respective case
# prevent $ next and $ succ errors
vowel_crosswalk = {
"a"=>"e",
"A"=>"E",
"e"=>"i",
"E"=>"I",
"i"=>"o",
"I"=>"O",
"o"=>"u",
"O"=>"U",
"u"=>"a",
"U"=>"A"
}
# set hash for all consonants in caps and lower for rotate one forward (toward z)
# z and Z becomes a and A, respectively, to prevent $ next and $ succ errors
consonant_crosswalk = {
"a" =>"b",
"b" =>"c",
"c" =>"d",
"d" =>"f",
"f" =>"g",
"g" =>"h",
"h" =>"j",
"j" =>"k",
"k" =>"l",
"l" =>"m",
"m" =>"n",
"n" =>"p",
"p" =>"q",
"q" =>"r",
"r" =>"s",
"s" =>"t",
"t" =>"v",
"v" =>"w",
"w" =>"x",
"x" =>"y",
"z" =>"a",
"A" =>"B",
"B" =>"C",
"C" =>"D",
"D" =>"F",
"F" =>"G",
"G" =>"H",
"H" =>"J",
"J" =>"K",
"K" =>"L",
"L" =>"M",
"M" =>"N",
"N" =>"P",
"P" =>"Q",
"Q" =>"R",
"R" =>"S",
"S" =>"T",
"T" =>"V",
"V" =>"W",
"W" =>"X",
"X" =>"Y",
"Y" =>"Z",
"Z" =>"A"
}
# use the hash keys to find using gsub their rotated value
# join brings it together so gsub can iterate through and replace pattern
vowel_find = /[#{vowel_crosswalk.keys.join}]/
vowel_next_name = last_first.gsub(vowel_find, vowel_crosswalk)
consonant_find = /[#{consonant_crosswalk.keys.join}]/
alias_name = vowel_next_name.gsub(consonant_find, consonant_crosswalk)
# prints new alias_name output so each user gets their full name conversion
# fulfills release 1 request for individual user
# add quit == flase, so that in release 2, it doesn't print last person's alias to quit user
# method would basically keep running and output last alias as well
# individual users still need their alias, database manager doesn't need an alias ;)
# need an if not a while or until so last alias name doesn't keep running
if quit == false
puts alias_name
end
# store alias and iterate through hash for new names
# fulfills release 2 request for admin who gets all the hash keys and values
name_hash.merge! full_name => alias_name
# end the until quit is true loop
end
# end the method
end
# call the method
alias_maker(full_name)
|
json.array!(@events) do |event|
json.extract! event, :id, :name, :price
json.start event.created_at
json.title "#{event.name}:#{event.price}円"
json.allDay true
json.url wasting_url(event)
end |
desc "Create basic user roles"
task seed_roles: :environment do
if Common::Role.count == 0
Common::Role.create!([
{ name: Constants::SUPER_ADMIN, built_in: true },
# { name: "Admin" },
# { name: "Book Keeper" },
# { name: "Business Manager" },
# { name: "Business Owner" },
# { name: "Extraction Supervisor" },
# { name: "Gardener" },
# { name: "Inventory Supervisor" },
# { name: "Lab Assistant" },
# { name: "Packager" },
# { name: "Supervisors" },
])
end
end
|
require 'rails_helper'
RSpec.describe "Items", type: :request do
describe "GET /items" do
it "listing all items" do
create(:item)
create(:item)
get items_path
expect(response).to have_http_status(200)
end
it 'list one item' do
item = create(:item)
get "/items/#{item.id}"
expect(response.body).to include_json(
description: item.description
)
end
end
end
|
class Destination < ApplicationRecord
has_many :posts
has_many :bloggers, through: :posts
def posts_about_me
self.posts.all
end
end
|
class InternetsController < ApplicationController
before_action :set_internet, only: [:show, :edit, :update, :destroy]
# GET /internets
# GET /internets.json
def index
@internets = Internet.all
end
# GET /internets/1
# GET /internets/1.json
def show
end
# GET /internets/new
def new
@internet = Internet.new
end
# GET /internets/1/edit
def edit
end
# POST /internets
# POST /internets.json
def create
@internet = Internet.new(internet_params)
respond_to do |format|
if @internet.save
format.html { redirect_to @internet, notice: 'Internet was successfully created.' }
format.json { render :show, status: :created, location: @internet }
else
format.html { render :new }
format.json { render json: @internet.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /internets/1
# PATCH/PUT /internets/1.json
def update
respond_to do |format|
if @internet.update(internet_params)
format.html { redirect_to @internet, notice: 'Internet was successfully updated.' }
format.json { render :show, status: :ok, location: @internet }
else
format.html { render :edit }
format.json { render json: @internet.errors, status: :unprocessable_entity }
end
end
end
# DELETE /internets/1
# DELETE /internets/1.json
def destroy
@internet.destroy
respond_to do |format|
format.html { redirect_to internets_url, notice: 'Internet was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_internet
@internet = Internet.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def internet_params
params.require(:internet).permit(:banda, :contrato, :cnpj, :nome)
end
end
|
module SelfieChain
class Wrapper < BasicObject
def initialize(subject)
@subject = subject
end
def method_missing(method, *args, &block)
if !@subject.nil? && @subject.respond_to?(method)
@subject = @subject.public_send(method, *args, &block)
end
self
end
# returns @subject or other, if the optional block evaluates to true (and @subject is not nil)
def share_selfie(other = nil, &block)
# this means it's NOT equivalent to .share_selfie.selfie(other, &block)
return if @subject.nil?
# block_given? isn't defined on BasicObject
if block.nil?
@subject
else
yield(@subject) ? @subject : other
end
end
end
end |
module CollectionHelper
def collection_items(options={})
items = Spree::Variant.where(is_master: true).joins(:images).uniq
return items unless options[:preview]
items.select{|v| v.product.showcased }
end
def collection_thumbnail(img_path)
image_tag img_path, title: "furniture collection pull-sku-from-record", class: "collection-image"
end
def collection_image_reference(variant, options={})
content_tag :figure do
link_to collection_image_thumbnail_tag(variant), variant.collection_image.attachment.url(:large), class: 'collection-img-link'
end
end
def grid_item_dom_klass(index)
dom_class = "grid-item col-md-4 col-sm-6"
return "#{dom_class} double-right-border" if index % 3 == 0
return "#{dom_class} double-left-border" if (index - 1) % 3 == 0
"#{dom_class} large-borders"
end
def preview_reference(image)
path = "preview/#{image}"
content_tag :figure do
link_to collection_thumbnail(path), "assets/#{path}", class: 'collection-img-link'
end
end
private
def collection_image_thumbnail_tag(variant)
image_tag variant.collection_image.attachment.url(:preview), alt: "#{variant.name.gsub(/\s+/, "").underscore.dasherize}", class: "collection-image"
end
end
|
require 'set'
module VWorkApp
class Base
include ActiveModel::Serializers::JSON
include ActiveModel::Serializers::Xml
include ActiveModel::Validations
def initialize(attributes = {})
self.attributes = attributes
end
# -----------------
# Hattr Methods
# ----------------
def self.hattr_reader(*hattrs)
hattrs.each do |hattr|
self.read_hattrs << hattr
attr_reader(hattr.is_a?(Hash) ? hattr.keys.first : hattr)
end
end
def self.hattr_writer(*hattrs)
hattrs.each do |hattr|
self.write_hattrs << hattr
attr_writer(hattr.is_a?(Hash) ? hattr.keys.first : hattr)
end
end
def self.hattr_accessor(*hattrs)
hattr_reader(*hattrs)
hattr_writer(*hattrs)
end
def self.write_hattrs
@write_hattrs ||= Set.new
end
def write_hattrs
self.class.write_hattrs
end
def self.read_hattrs
@read_hattrs ||= Set.new
end
def read_hattrs
self.class.read_hattrs
end
def self.hattrs
read_hattrs + write_hattrs
end
def hattrs
self.class.hattrs
end
# -------------------
# Attributes Methods
# -------------------
def attributes
extract_attributes(hattrs)
end
def read_attributes
extract_attributes(read_hattrs)
end
def write_attributes
extract_attributes(write_hattrs)
end
def attributes=(hash)
inject_attributes(hattrs, hash)
end
def write_attributes=(hash)
inject_attributes(write_hattrs, hash)
end
def read_attributes=(hash)
inject_attributes(read_hattrs, hash)
end
# -----------------
# Misc Methods
# -----------------
def validate_and_raise
raise Exception.new(self.errors.full_messages.join("\n")) unless valid?
end
def attributes_eql?(other, *test_attrs)
test_attrs.each do |attribute|
return false unless self.send(attribute.to_sym) == other.send(attribute.to_sym)
end
true
end
private
def extract_attributes(hattrs)
attr = hattrs.map do |hattr|
hattr = hattr.keys.first if hattr.is_a?(Hash)
[hattr.to_s, send(hattr)]
end
Hash[attr]
end
def inject_attributes(hattrs, hash)
hash = Hash[hash.map { |k,v| [k.to_sym, v] }]
hattrs.each do |hattr|
value = case hattr
when Hash
hattr, klass = hattr.first
next unless hash[hattr.to_sym]
klass.is_a?(Array) ? hash[hattr.to_sym].map {|h| klass.first.new(h)} : klass.new(hash[hattr.to_sym])
else
next unless hash[hattr.to_sym]
hash[hattr.to_sym]
end
set_hattr(hattr, value)
end
end
def set_hattr(hattr, value)
write_hattrs.include?(hattr) ? send("#{hattr}=", value) : self.instance_variable_set("@#{hattr.to_s}", value)
end
end
end
# -----------------
# AM Monkey Patches. Yuk.
# -----------------
module ActiveModel::Serialization
def serializable_hash(options = nil)
options ||= {}
only = Array.wrap(options[:only]).map(&:to_s)
except = Array.wrap(options[:except]).map(&:to_s)
# AF: Changed to write_attributes
attribute_names = write_attributes.keys.sort
if only.any?
attribute_names &= only
elsif except.any?
attribute_names -= except
end
method_names = Array.wrap(options[:methods]).map { |n| n if respond_to?(n.to_s) }.compact
Hash[(attribute_names + method_names).map { |n| [n, send(n)] }]
end
end
module ActiveModel::Serializers::Xml
class Serializer
def attributes_hash
# AF: Changed to write_attributes
attributes = @serializable.write_attributes
if options[:only].any?
attributes.slice(*options[:only])
elsif options[:except].any?
attributes.except(*options[:except])
else
attributes
end
end
end
end
|
require_relative '../acceptance_helper'
feature 'create answer' do
given!(:current_user) { create(:user) }
given!(:other_user) { create(:user) }
given!(:question) { create(:question, user: current_user) }
given!(:other_question) { create(:question, user: other_user) }
scenario 'guest tries to answer question', js: true do
visit question_path(question)
expect(page).to_not have_selector(:link_or_button, 'Ответить')
end
scenario "user creates answer to your question", js: true do
sign_in(current_user)
visit question_path(question)
fill_in 'field_answer', with: "text text text"
click_on "Ответить"
within '#answers' do
expect(page).to have_content "text text text"
end
end
scenario "user create answer foregin question", js: true do
sign_in(current_user)
visit question_path(other_question)
fill_in 'field_answer', with: "text text text"
click_on "Ответить"
within '#answers' do
expect(page).to have_content "text text text"
end
end
scenario "user tries create answer with invalid data", js: true do
sign_in(current_user)
visit question_path(question)
click_on "Ответить"
expect(page).to have_content "Content не может быть пустым"
end
end
|
class Podcast < ActiveRecord::Base
outpost_model
has_secretary
include Concern::Callbacks::SphinxIndexCallback
ROUTE_KEY = "podcast"
ITEM_TYPES = [
["Episodes", 'episodes'],
["Segments", 'segments'],
["Content", 'content']
]
SOURCES = ["KpccProgram", "ExternalProgram", "Blog"]
CONTENT_CLASSES = [
NewsStory,
ShowSegment,
BlogEntry
]
#-------------
# Scopes
#-------------
# Association
belongs_to :source, polymorphic: true
belongs_to :category
#-------------
# Validation
validates :slug, uniqueness: true, presence: true
validates :title, presence: true
validates :url, presence: true, url: true
validates :podcast_url, presence: true, url: true
validates :itunes_url, url: { allow_blank: true }
validates :image_url, url: { allow_blank: true }
#-------------
# Callbacks
#-------------
# Sphinx
define_index do
indexes title, sortable: true
indexes slug
indexes description
end
#-------------
def content(limit=25)
@content ||= begin
klasses = []
conditions = {}
case self.source_type
when "KpccProgram"
conditions.merge!(program: self.source.id)
klasses.push ShowEpisode if self.item_type == "episodes"
klasses.push ShowSegment if self.item_type == "segments"
when "ExternalProgram"
# ExternalProgram won't actually have any content
# So, just incase this method gets called,
# just return an empty array.
return []
when "Blog"
conditions.merge!(blog: self.source.id)
klasses.push BlogEntry
else
klasses = [NewsStory, BlogEntry, ShowSegment, ShowEpisode] if item_type == "content"
end
results = content_query(limit, klasses, conditions)
results.map(&:to_article)
end
end
#-------------
def route_hash
return {} if !self.persisted?
{ slug: self.slug }
end
#-------------
private
def content_query(limit, klasses, conditions={})
ContentBase.search({
:with => conditions.reverse_merge({
:has_audio => true
}),
:classes => klasses,
:limit => limit
})
end
end
|
class CreateProviders < ActiveRecord::Migration
def change
create_table :providers do |t|
t.belongs_to :location, index: true
t.string :title
t.string :name
t.string :photo_url
t.string :profile_url
t.string :email
t.string :phone_number
t.boolean :sliding_scale, default: false
t.integer :min_price, default: 0
t.integer :max_price, default: 0
t.timestamps
end
end
end
|
class AddItemDeliveryFeeToShop < ActiveRecord::Migration
def change
add_column :shops, :item_delivery_fee, :jsonb, default: {}
end
end
|
require 'test_helper'
class SpaceTest < Test::Unit::TestCase
def test_should_find_single_space
space = Podio::Space.find(1)
assert_equal 1, space['space_id']
assert_equal 'API', space['name']
end
def test_should_find_all_for_org
spaces = Podio::Space.find_all_for_org(1)
assert spaces.is_a?(Array)
assert_not_nil spaces.first['name']
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.