text stringlengths 10 2.61M |
|---|
module Apotomo
# Methods needed to serialize the widget tree and back.
module Persistence
def self.included(base)
base.extend(ClassMethods)
end
# For Ruby 1.8/1.9 compatibility.
def symbolized_instance_variables
instance_variables.map { |ivar| ivar.to_sym }
end
def freeze_ivars_to(storage)
frozen = {}
(symbolized_instance_variables - unfreezable_ivars).each do |ivar|
frozen[ivar] = instance_variable_get(ivar)
end
storage[path] = frozen
end
### FIXME: rewrite so that root might be stateless as well.
def freeze_data_to(storage)
freeze_ivars_to(storage)# if self.kind_of?(StatefulWidget)
children.each { |child| child.freeze_data_to(storage) if child.kind_of?(StatefulWidget) }
end
def freeze_to(storage)
storage[:apotomo_root] = self # save structure.
storage[:apotomo_widget_ivars] = {}
freeze_data_to(storage[:apotomo_widget_ivars]) # save ivars.
end
def thaw_ivars_from(storage)
storage.fetch(path, {}).each do |k, v|
instance_variable_set(k, v)
end
end
def thaw_data_from(storage)
thaw_ivars_from(storage)
children.each { |child| child.thaw_data_from(storage) }
end
def dump_tree
collect { |n| [n.class, n.name, n.root? ? nil : n.parent.name] }
end
module ClassMethods
# Dump the shit to storage.
def freeze_for(storage, root)
storage[:apotomo_stateful_branches] = []
storage[:apotomo_widget_ivars] = {}
stateful_branches_for(root).each do |branch|
branch.freeze_data_to(storage[:apotomo_widget_ivars]) # save ivars.
storage[:apotomo_stateful_branches] << branch.dump_tree
end
end
# Create tree from storage and add branches to root/stateless parents.
def thaw_for(controller, storage, root)
branches = storage.delete(:apotomo_stateful_branches) || []
branches.each do |data|
branch = load_tree(controller, data)
parent = root.find_widget(data.first.last) or raise "Couldn't find parent `#{data.first.last}` for `#{branch.name}`"
parent << branch
branch.thaw_data_from(storage.delete(:apotomo_widget_ivars) || {})
end
root
end
def frozen_widget_in?(storage)
storage[:apotomo_stateful_branches].kind_of? Array
end
def flush_storage(storage)
storage[:apotomo_stateful_branches] = nil
storage[:apotomo_widget_ivars] = nil
end
# Find the first stateful widgets on each branch from +root+.
def stateful_branches_for(root)
to_traverse = [root]
stateful_roots = []
while node = to_traverse.shift
if node.kind_of?(StatefulWidget)
stateful_roots << node and next
end
to_traverse += node.children
end
stateful_roots
end
private
def load_tree(parent_controller, cold_widgets)
root = nil
cold_widgets.each do |data|
node = data[0].new(parent_controller, data[1], "")
root = node and next unless root
root.find_widget(data[2]) << node
end
root
end
end
end
end
|
class Event < ActiveRecord::Base
# include helper module for query caching
include Cacheable
# include event processing
include Processable
# include doi normalization
include Identifiable
# include helper module for Elasticsearch
include Indexable
include Elasticsearch::Model
before_validation :set_defaults
validates :uuid, format: { with: /\A[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\z/i }
# include state machine
include AASM
aasm :whiny_transitions => false do
state :waiting, :initial => true
state :working, :failed, :done
# Reset after failure
event :reset do
transitions from: [:failed], to: :waiting
end
event :start do
transitions from: [:waiting], to: :working
end
event :finish do
transitions from: [:working], to: :done
end
event :error do
transitions to: :failed
end
end
# after_transition :to => [:failed, :done] do |event|
# event.send_callback if event.callback.present?
# end
# after_transition :failed => :waiting do |event|
# event.queue_event_job
# end
serialize :subj, JSON
serialize :obj, JSON
serialize :error_messages, JSON
INCLUDED_RELATION_TYPES = [
"cites", "is-cited-by",
"compiles", "is-compiled-by",
"documents", "is-documented-by",
"has-metadata", "is-metadata-for",
"is-supplement-to", "is-supplemented-by",
"is-derived-from", "is-source-of",
"references", "is-referenced-by",
"reviews", "is-reviewed-by",
"requires", "is-required-by",
"describes", "is-described-by"
]
validates :subj_id, :source_id, :source_token, presence: true
attr_accessor :container_title, :url
# use different index for testing
index_name Rails.env.test? ? "events-test" : "events"
mapping dynamic: 'false' do
indexes :uuid, type: :keyword
indexes :subj_id, type: :keyword
indexes :obj_id, type: :keyword
indexes :doi, type: :keyword
indexes :orcid, type: :keyword
indexes :prefix, type: :keyword
indexes :subtype, type: :keyword
indexes :citation_type, type: :keyword
indexes :issn, type: :keyword
indexes :subj, type: :object, properties: {
"@type" => { type: :keyword },
"@id" => { type: :keyword },
uid: { type: :keyword },
name: { type: :text },
givenName: { type: :text },
familyName: { type: :text },
author: { type: :object, properties: {
"@type" => { type: :keyword },
"@id" => { type: :keyword },
name: { type: :text },
givenName: { type: :text },
familyName: { type: :text }
}},
periodical: { type: :object, properties: {
"@type" => { type: :keyword },
"@id" => { type: :keyword },
name: { type: :text },
"issn" => { type: :keyword }
}},
alternateName: { type: :text },
volumeNumber: { type: :keyword },
issueNumber: { type: :keyword },
pagination: { type: :keyword },
publisher: { type: :object, properties: {
"@type" => { type: :keyword },
"@id" => { type: :keyword },
name: { type: :text }
}},
funder: { type: :object, properties: {
"@type" => { type: :keyword },
"@id" => { type: :keyword },
name: { type: :text }
}},
proxyIdentifiers: { type: :keyword },
version: { type: :keyword },
datePublished: { type: :date, format: "date_optional_time||yyyy-MM-dd||yyyy-MM||yyyy", ignore_malformed: true },
dateModified: { type: :date, format: "date_optional_time", ignore_malformed: true },
registrantId: { type: :keyword },
cache_key: { type: :keyword }
}
indexes :obj, type: :object, properties: {
type: { type: :keyword },
id: { type: :keyword },
uid: { type: :keyword },
name: { type: :text },
givenName: { type: :text },
familyName: { type: :text },
author: { type: :object, properties: {
"@type" => { type: :keyword },
"@id" => { type: :keyword },
name: { type: :text },
givenName: { type: :text },
familyName: { type: :text }
}},
periodical: { type: :object, properties: {
"@type" => { type: :keyword },
"@id" => { type: :keyword },
name: { type: :text },
"issn" => { type: :keyword }
}},
alternateName: { type: :text },
volumeNumber: { type: :keyword },
issueNumber: { type: :keyword },
pagination: { type: :keyword },
publisher: { type: :object, properties: {
"@type" => { type: :keyword },
"@id" => { type: :keyword },
name: { type: :text }
}},
funder: { type: :object, properties: {
"@type" => { type: :keyword },
"@id" => { type: :keyword },
name: { type: :text }
}},
proxyIdentifiers: { type: :keyword },
version: { type: :keyword },
datePublished: { type: :date, format: "date_optional_time||yyyy-MM-dd||yyyy-MM||yyyy", ignore_malformed: true },
dateModified: { type: :date, format: "date_optional_time", ignore_malformed: true },
registrantId: { type: :keyword },
cache_key: { type: :keyword }
}
indexes :source_id, type: :keyword
indexes :source_token, type: :keyword
indexes :message_action, type: :keyword
indexes :relation_type_id, type: :keyword
indexes :registrant_id, type: :keyword
indexes :access_method, type: :keyword
indexes :metric_type, type: :keyword
indexes :total, type: :integer
indexes :license, type: :text, fields: { keyword: { type: "keyword" }}
indexes :error_messages, type: :object
indexes :callback, type: :text
indexes :aasm_state, type: :keyword
indexes :state_event, type: :keyword
indexes :year_month, type: :keyword
indexes :created_at, type: :date
indexes :updated_at, type: :date
indexes :indexed_at, type: :date
indexes :occurred_at, type: :date
indexes :cache_key, type: :keyword
end
def as_indexed_json(options={})
{
"uuid" => uuid,
"subj_id" => subj_id,
"obj_id" => obj_id,
"subj" => subj.merge(cache_key: subj_cache_key),
"obj" => obj.merge(cache_key: obj_cache_key),
"doi" => doi,
"orcid" => orcid,
"issn" => issn,
"prefix" => prefix,
"subtype" => subtype,
"citation_type" => citation_type,
"source_id" => source_id,
"source_token" => source_token,
"message_action" => message_action,
"relation_type_id" => relation_type_id,
"registrant_id" => registrant_id,
"access_method" => access_method,
"metric_type" => metric_type,
"total" => total,
"license" => license,
"error_messages" => error_messages,
"aasm_state" => aasm_state,
"state_event" => state_event,
"year_month" => year_month,
"created_at" => created_at,
"updated_at" => updated_at,
"indexed_at" => indexed_at,
"occurred_at" => occurred_at,
"cache_key" => cache_key
}
end
def self.query_fields
['subj_id^10', 'obj_id^10', 'subj.name^5', 'subj.author^5', 'subj.periodical^5', 'subj.publisher^5', 'obj.name^5', 'obj.author^5', 'obj.periodical^5', 'obj.publisher^5', '_all']
end
def self.query_aggregations
sum_distribution = {
sum_bucket: {
buckets_path: "year_months>total_by_year_month"
}
}
sum_year_distribution = {
sum_bucket: {
buckets_path: "years>total_by_year"
}
}
{
sources: { terms: { field: 'source_id', size: 50, min_doc_count: 1 } },
prefixes: { terms: { field: 'prefix', size: 50, min_doc_count: 1 } },
registrants: { terms: { field: 'registrant_id', size: 50, min_doc_count: 1 }, aggs: { year: { date_histogram: { field: 'occurred_at', interval: 'year', min_doc_count: 1 }, aggs: { "total_by_year" => { sum: { field: 'total' }}}}} },
pairings: { terms: { field: 'registrant_id', size: 50, min_doc_count: 1 }, aggs: { recipient: { terms: { field: 'registrant_id', size: 50, min_doc_count: 1 }, aggs: { "total" => { sum: { field: 'total' }}}}} },
citation_types: { terms: { field: 'citation_type', size: 50, min_doc_count: 1 }, aggs: { year_months: { date_histogram: { field: 'occurred_at', interval: 'month', min_doc_count: 1 }, aggs: { "total_by_year_month" => { sum: { field: 'total' }}}}} },
relation_types: { terms: { field: 'relation_type_id', size: 50, min_doc_count: 1 }, aggs: { year_months: { date_histogram: { field: 'occurred_at', interval: 'month', min_doc_count: 1 }, aggs: { "total_by_year_month" => { sum: { field: 'total' }}}},"sum_distribution"=>sum_distribution} },
dois: { terms: { field: 'obj_id', size: 50, min_doc_count: 1 }, aggs: { relation_types: { terms: { field: 'relation_type_id',size: 50, min_doc_count: 1 }, aggs: { "total_by_type" => { sum: { field: 'total' }}}}} },
dois_usage: {
filter: { script: { script: "doc['source_id'].value == 'datacite-usage' && doc['occurred_at'].value.getMillis() >= doc['obj.datePublished'].value.getMillis() && doc['occurred_at'].value.getMillis() < new Date().getTime()" }},
aggs: {
dois: { terms: { field: 'obj_id', size: 50, min_doc_count: 1 }, aggs: { relation_types: { terms: { field: 'relation_type_id',size: 50, min_doc_count: 1 }, aggs: { "total_by_type" => { sum: { field: 'total' }}}}} } }
},
dois_citations: {
filter: {
script: {
script: "#{INCLUDED_RELATION_TYPES}.contains(doc['relation_type_id'].value)"
}
},
aggs: { years: { date_histogram: { field: 'occurred_at', interval: 'year', min_doc_count: 1 }, aggs: { "total_by_year" => { sum: { field: 'total' }}}},"sum_distribution"=>sum_year_distribution}
}
}
end
def self.index(options={})
from_id = (options[:from_id] || 1).to_i
until_id = (options[:until_id] || from_id + 499).to_i
# get every id between from_id and until_id
(from_id..until_id).step(500).each do |id|
EventIndexByIdJob.perform_later(id: id)
puts "Queued indexing for events with IDs starting with #{id}."
end
end
def self.index_by_id(options={})
return nil unless options[:id].present?
id = options[:id].to_i
errors = 0
count = 0
logger = Logger.new(STDOUT)
Event.where(id: id..(id + 499)).find_in_batches(batch_size: 500) do |events|
response = Event.__elasticsearch__.client.bulk \
index: Event.index_name,
type: Event.document_type,
body: events.map { |event| { index: { _id: event.id, data: event.as_indexed_json } } }
# log errors
errors += response['items'].map { |k, v| k.values.first['error'] }.compact.length
response['items'].select { |k, v| k.values.first['error'].present? }.each do |err|
logger.error "[Elasticsearch] " + err.inspect
end
count += events.length
end
if errors > 1
logger.error "[Elasticsearch] #{errors} errors indexing #{count} events with IDs #{id} - #{(id + 499)}."
elsif count > 0
logger.info "[Elasticsearch] Indexed #{count} events with IDs #{id} - #{(id + 499)}."
end
rescue Elasticsearch::Transport::Transport::Errors::RequestEntityTooLarge, Faraday::ConnectionFailed, ActiveRecord::LockWaitTimeout => error
logger.info "[Elasticsearch] Error #{error.message} indexing events with IDs #{id} - #{(id + 499)}."
count = 0
Event.where(id: id..(id + 499)).find_each do |event|
IndexJob.perform_later(event)
count += 1
end
logger.info "[Elasticsearch] Indexed #{count} events with IDs #{id} - #{(id + 499)}."
end
def to_param # overridden, use uuid instead of id
uuid
end
def send_callback
data = { "data" => {
"id" => uuid,
"type" => "events",
"state" => aasm_state,
"errors" => error_messages,
"messageAction" => message_action,
"sourceToken" => source_token,
"total" => total,
"timestamp" => timestamp }}
Maremma.post(callback, data: data.to_json, token: ENV['API_KEY'])
end
def access_method
if relation_type_id.to_s =~ /(requests|investigations)/
relation_type_id.split("-").last if relation_type_id.present?
end
end
def metric_type
if relation_type_id.to_s =~ /(requests|investigations)/
arr = relation_type_id.split("-", 4)
arr[0..2].join("-")
end
end
def doi
Array.wrap(subj["proxyIdentifiers"]).grep(/\A10\.\d{4,5}\/.+\z/) { $1 } +
Array.wrap(obj["proxyIdentifiers"]).grep(/\A10\.\d{4,5}\/.+\z/) { $1 } +
Array.wrap(subj["funder"]).map { |f| doi_from_url(f["@id"]) }.compact +
Array.wrap(obj["funder"]).map { |f| doi_from_url(f["@id"]) }.compact +
[doi_from_url(subj_id), doi_from_url(obj_id)].compact
end
def prefix
[doi.map { |d| d.to_s.split('/', 2).first }].compact
end
def orcid
Array.wrap(subj["author"]).map { |f| orcid_from_url(f["@id"]) }.compact +
Array.wrap(obj["author"]).map { |f| orcid_from_url(f["@id"]) }.compact +
[orcid_from_url(subj_id), orcid_from_url(obj_id)].compact
end
def issn
Array.wrap(subj.dig("periodical", "issn")).compact +
Array.wrap(obj.dig("periodical", "issn")).compact
rescue TypeError
nil
end
def registrant_id
[subj["registrantId"], obj["registrantId"], subj["provider_id"], obj["provider_id"]].compact
end
def subtype
[subj["@type"], obj["@type"]].compact
end
def citation_type
return nil if subj["@type"].blank? || subj["@type"] == "CreativeWork" || obj["@type"].blank? || obj["@type"] == "CreativeWork"
[subj["@type"], obj["@type"]].compact.sort.join("-")
end
def doi_from_url(url)
if /\A(?:(http|https):\/\/(dx\.)?(doi.org|handle.test.datacite.org)\/)?(doi:)?(10\.\d{4,5}\/.+)\z/.match(url)
uri = Addressable::URI.parse(url)
uri.path.gsub(/^\//, '').downcase
end
end
def orcid_from_url(url)
Array(/\A(http|https):\/\/orcid\.org\/(.+)/.match(url)).last
end
def timestamp
updated_at.utc.iso8601 if updated_at.present?
end
def year_month
occurred_at.utc.iso8601[0..6] if occurred_at.present?
end
def cache_key
timestamp = updated_at || Time.zone.now
"events/#{uuid}-#{timestamp.iso8601}"
end
def subj_cache_key
timestamp = subj["dateModified"] || Time.zone.now.iso8601
"objects/#{subj_id}-#{timestamp}"
end
def obj_cache_key
timestamp = obj["dateModified"] || Time.zone.now.iso8601
"objects/#{obj_id}-#{timestamp}"
end
def set_defaults
self.uuid = SecureRandom.uuid if uuid.blank?
self.subj_id = normalize_doi(subj_id) || subj_id
self.obj_id = normalize_doi(obj_id) || obj_id
# make sure subj and obj have correct id
self.subj = subj.to_h.merge("id" => self.subj_id)
self.obj = obj.to_h.merge("id" => self.obj_id)
self.total = 1 if total.blank?
self.relation_type_id = "references" if relation_type_id.blank?
self.occurred_at = Time.zone.now.utc if occurred_at.blank?
self.license = "https://creativecommons.org/publicdomain/zero/1.0/" if license.blank?
end
end |
module Erp
class ApplicationMailer < ActionMailer::Base
default from: "soft.support@hoangkhang.com.vn"
layout 'mailer'
private
def send_email(email, subject)
#@todo static email!!
delivery_options = {
address: 'smtp.gmail.com',
port: 587,
domain: 'globalnaturesoft.com',
user_name: 'soft.support@hoangkhang.com.vn',
password: 'aA456321@#$',
authentication: 'plain',
enable_starttls_auto: true
}
mail(to: email,
subject: subject,
delivery_method_options: delivery_options)
end
end
end
|
# $LICENSE
# Copyright 2013-2014 Spotify AB. All rights reserved.
#
# The contents of this file are 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.
require_relative 'shared'
module FFWD::Plugin::Riemann
module Output
def send_all events, metrics
all_events = []
events.each do |event|
begin
all_events << make_event(event)
rescue => error
output_failed_event event, error
end
end
metrics.each do |metric|
begin
all_events << make_metric(metric)
rescue => error
output_failed_metric metric, error
end
end
return if all_events.empty?
m = make_message :events => all_events
send_data output_encode(m)
end
def send_event event
begin
e = make_event event
rescue => error
output_failed_event event, error
return
end
m = make_message :events => [e]
send_data output_encode(m)
end
def send_metric metric
begin
e = make_metric metric
rescue => error
output_failed_metric event, error
return
end
m = make_message :events => [e]
send_data output_encode(m)
end
def receive_data data
message = read_message data
return if message.ok
@bad_acks = (@bad_acks || 0) + 1
end
def output_encode message
raise "#output_encode: not implemented"
end
def output_failed_event event, error; end
def output_failed_metric metric, error; end
end
end
|
require 'rails_helper'
describe ReviewsController do
let(:valid_attributes) { attributes_for :review }
let(:invalid_attributes) { attributes_for :review, msg: "" }
describe "GET #index" do
it "assigns all reviews as @reviews" do
review = Review.create! valid_attributes
get :index, {}
expect(assigns(:reviews)).to eq([review])
end
end
describe "GET #show" do
it "assigns the requested review as @review" do
review = Review.create! valid_attributes
get :show, { id: review.to_param }
expect(assigns(:review)).to eq(review)
end
end
describe "GET #new" do
it "assigns a new review as @review" do
get :new, {}
expect(assigns(:review)).to be_a_new(Review)
end
end
describe "GET #edit" do
it "assigns the requested review as @review" do
review = Review.create! valid_attributes
get :edit, { id: review.to_param }
expect(assigns(:review)).to eq(review)
end
end
describe "POST #create" do
context "with valid params" do
it "creates a new Review" do
expect { post :create, { review: valid_attributes }}.to change(Review, :count).by(1)
end
it "assigns a newly created review as @review" do
post :create, { review: valid_attributes }
expect(assigns(:review)).to be_a(Review)
expect(assigns(:review)).to be_persisted
end
it "redirects to the created review" do
post :create, { review: valid_attributes }
expect(response).to redirect_to(Review.last)
end
end
context "with invalid params" do
it "assigns a newly created but unsaved review as @review" do
post :create, { review: invalid_attributes }
expect(assigns(:review)).to be_a_new(Review)
end
it "re-renders the 'new' template" do
post :create, { review: invalid_attributes }
expect(response).to render_template("new")
end
end
end
describe "PUT #update" do
context "with valid params" do
let(:new_attributes) { attributes_for :review, msg: "New Review" }
it "updates the requested review" do
review = Review.create! valid_attributes
put :update, { id: review.to_param, review: new_attributes }
review.reload
expect(review.msg).to eq "New Review"
end
it "assigns the requested review as @review" do
review = Review.create! valid_attributes
put :update, { id: review.to_param, review: valid_attributes }
expect(assigns(:review)).to eq(review)
end
it "redirects to the review" do
review = Review.create! valid_attributes
put :update, { id: review.to_param, review: valid_attributes }
expect(response).to redirect_to(review)
end
end
context "with invalid params" do
it "assigns the review as @review" do
review = Review.create! valid_attributes
put :update, { id: review.to_param, review: invalid_attributes }
expect(assigns(:review)).to eq(review)
end
it "re-renders the 'edit' template" do
review = Review.create! valid_attributes
put :update, { id: review.to_param, review: invalid_attributes }
expect(response).to render_template("edit")
end
end
end
describe "DELETE #destroy" do
it "destroys the requested review" do
review = Review.create! valid_attributes
expect { delete :destroy, { id: review.to_param }}.to change(Review, :count).by(-1)
end
it "redirects to the reviews list" do
review = Review.create! valid_attributes
delete :destroy, { id: review.to_param }
expect(response).to redirect_to(reviews_url)
end
end
end
|
# -*- encoding : utf-8 -*-
class ConfigAppsController < ApplicationController
load_and_authorize_resource #cancan
def show
@config_app = ConfigApp.find(params[:id])
end
def index
@config_app= ConfigApp.all
respond_to do |format|
format.html
format.js
end
end
def new
@config_app= ConfigApp.new
# respond_to do |format|
# format.html # new.html.erb
# format.json { render json: @product }
end
def create
@config_app= ConfigApp.new ( params[:config_app] )
respond_to do |format|
if @config_app.save
format.html { redirect_to @config_app, notice: 'Конфигурация успешно добавлена.' }
format.json { render json: @config_app, status: :created, location: @payment }
else
format.html { render action: "new" }
end
end
end
def destroy
@config_app = ConfigApp.find(params[:id])
respond_to do |format|
@config_app.destroy
format.html { redirect_to config_apps_url, notice: 'Конфигурация удалена!' }
format.json { head :no_content }
end
end
def edit
@config_app = ConfigApp.find(params[:id])
end
def update
@config_app = ConfigApp.find(params[:id])
respond_to do |format|
if @config_app.update_attributes(params[:config_app])
format.html { redirect_to @config_app, notice: 'Конфигурация успешно обновлена.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @payment.errors, status: :unprocessable_entity }
end
end
end
end
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :name
validates :slug, uniqueness: true
has_many :programs
before_validation :create_slug
def to_s
name
end
private
def create_slug
if self.slug.blank?
slug = self.name.downcase
i = 1
while User.find_by_slug(slug)
slug = "#{slug}#{i}"
i += 1
end
self.slug = slug
end
end
end
|
require 'minitest/autorun'
require 'minitest/reporters'
require 'minitest/skip_dsl'
# TODO: uncomment the next line once you start wave 3 and add lib/checking_account.rb
require_relative '../lib/checking_account'
# Because a CheckingAccount is a kind
# of Account, and we've already tested a bunch of functionality
# on Account, we effectively get all that testing for free!
# Here we'll only test things that are different.
# TODO: change 'xdescribe' to 'describe' to run these tests
describe "CheckingAccount" do
describe "#initialize" do
# Check that a CheckingAccount is in fact a kind of account
it "Is a kind of Account" do
account = Bank::CheckingAccount.new(12345, 100.0)
account.must_be_kind_of Bank::Account
end
end # End describe "#initialize"
describe "#withdraw" do
it "Applies a $1 fee each time" do
# TODO: Your test code here!
checking_account = Bank::CheckingAccount.new(1337, 200)
withdrawal_amount = 99
new_balance = checking_account.withdraw(withdrawal_amount)
new_balance.must_equal withdrawal_amount + 1, "$1 fee is not withdrawn from the savings account"
checking_account.balance.must_equal withdrawal_amount + 1, "$1 fee is not withdrawn from the savings account"
end
it "Doesn't modify the balance if the fee would put it negative" do
# TODO: Your test code here!
start_balance = 200
withdrawal_amount = 200
checking_account = Bank::CheckingAccount.new(1337, start_balance)
updated_balance = checking_account.withdraw(withdrawal_amount)
# Both the value returned and the balance in the account
# must be un-modified.
updated_balance.must_equal start_balance
checking_account.balance.must_equal start_balance
end
end # End describe "#withdraw"
describe "#withdraw_using_check" do
it "Reduces the balance" do
# TODO: Your test code here!
start_balance = 200
check_amount = 25
checking_account = Bank::CheckingAccount.new(1337, start_balance)
reduced_balance = checking_account.withdraw_using_check(check_amount)
reduced_balance.must_be :< ,start_balance , "The balance is not reduced"
end
it "Returns the modified balance" do
# TODO: Your test code here!
start_balance = 200
check_amount = 25
checking_account = Bank::CheckingAccount.new(1337, start_balance)
new_balance = checking_account.withdraw_using_check(check_amount)
new_balance.must_equal start_balance - check_amount, "A modified balance is not returned"
checking_account.balance.must_equal new_balance, "The balance in the account is not the same as the return value of #withdraw_using_check"
end
it "Allows the balance to go down to -$10" do
# TODO: Your test code here!
start_balance = 200
check_amount = 210
checking_account = Bank::CheckingAccount.new(1337, start_balance)
negative_balance = checking_account.withdraw_using_check(check_amount)
negative_balance.must_be :>=, -10 , "The balance cannot go down to -$10"
end
it "Outputs a warning if the account would go below -$10" do
# TODO: Your test code here!
checking_account = Bank::CheckingAccount.new(1337, 200)
proc {
checking_account.withdraw_using_check(210.1)
}.must_raise ArgumentError
end
it "Doesn't modify the balance if the account would go below -$10" do
# TODO: Your test code here!
start_balance = 200
withdrawal_amount = 210.1
checking_account = Bank::CheckingAccount.new(1337, start_balance)
proc {
checking_account.withdraw_using_check(withdrawal_amount)
}.must_raise ArgumentError
checking_account.balance.must_equal start_balance, "The balance is not the same as start_balance"
end
it "Requires a positive withdrawal amount" do
# TODO: Your test code here!
start_balance = 200
withdrawal_amount = -1
checking_account = Bank::CheckingAccount.new(1337, start_balance)
proc {
checking_account.withdraw_using_check(withdrawal_amount)
}.must_raise ArgumentError
end
it "Allows 3 free uses" do
# TODO: Your test code here!
start_balance = 200
withdrawal_amount = 10
checking_account = Bank::CheckingAccount.new(1337, start_balance)
3.times do
checking_account.withdraw_using_check(withdrawal_amount)
end
checking_account.balance.must_equal (start_balance - 3 * withdrawal_amount) , "The resulting balance showsthat there is NOT 3 free uses"
end
it "Applies a $2 fee after the third use" do
# TODO: Your test code here!
start_balance = 200
withdrawal_amount = 10
fee = 2
checking_account = Bank::CheckingAccount.new(1337, start_balance)
4.times do
checking_account.withdraw_using_check(withdrawal_amount)
end
checking_account.balance.must_equal (start_balance - 4 * withdrawal_amount - fee) , "The resulting balance shows that the fee is not included"
end
it "Doesn't modify the balance if the account would go below -$10 due to the fee" do
# TODO: Your test code here!
start_balance = 30
withdrawal_amount = 10
checking_account = Bank::CheckingAccount.new(1337, start_balance)
3.times do
checking_account.withdraw_using_check(withdrawal_amount)
end
proc {
checking_account.withdraw_using_check(9)
}.must_raise ArgumentError
end
end # End describe "#withdraw_using_check"
describe "#reset_checks" do
it "Can be called without error" do
# TODO: Your test code here!
checking_account = Bank::CheckingAccount.new(1337, 200)
checking_account.reset_checks.must_equal 0, "Calling this method throws an error"
end
it "Makes the next three checks free if less than 3 checks had been used" do
# TODO: Your test code here!
start_balance = 200
withdrawal_amount = 10
checking_account = Bank::CheckingAccount.new(1337, start_balance)
2.times do
checking_account.withdraw_using_check(withdrawal_amount)
end
checking_account.reset_checks
3.times do
checking_account.withdraw_using_check(withdrawal_amount)
end
checking_account.balance.must_equal (start_balance - 5 * withdrawal_amount) , "Does NOT make the next three checks free if less than 3 checks had been used"
end
it "Makes the next three checks free if more than 3 checks had been used" do
# TODO: Your test code here!
start_balance = 200
withdrawal_amount = 10
fee = 2
checking_account = Bank::CheckingAccount.new(1337, start_balance)
4.times do
checking_account.withdraw_using_check(withdrawal_amount)
end
checking_account.reset_checks
3.times do
checking_account.withdraw_using_check(withdrawal_amount)
end
checking_account.balance.must_equal (start_balance - (4 * withdrawal_amount + fee) - 3 * withdrawal_amount) , "Does NOT
make the next three checks free if more than 3 checks had been used"
end
end # End describe "#reset_checks"
end # END describe "CheckingAccount"
|
# Создайте класс JellyBean,
# расширяющий класс Dessert (из Упражнения 11)
# новыми геттерами и сеттерами для атрибута flavor.
# Измените метод delicious? таким образом,
# чтобы он возвращал false только в тех случаях,
# когда flavor равняется «black licorice».
require_relative 'task_11.rb'
class JellyBean < Dessert
attr_accessor :flavor
def initialize(name, calories, flavor)
self.flavor = flavor
super(name, calories)
end
def delicious?
flavor != 'black licorice'
end
end
# TESTS
# bob = JellyBean.new("Cake", 450, "black licorice")
# puts bob.delicious?
# bob.flavor = "asf"
# puts bob.delicious?
# puts bob.name
# puts bob.healthy?
|
require 'vizier/registry'
require 'vizier/dsl/argument'
require 'vizier/task/base'
module Vizier
class << self
def describe_commands(name=nil, &block)
calling_file = CommandDescription.get_caller_file
name ||= File::basename(calling_file, ".rb")
CommandDescription.command(name, calling_file, &block).described
end
def extend_command(command, path, &block)
calling_file = CommandDescription.get_caller_file
CommandDescription.add_to(command, path, calling_file, &block)
end
#Backwards compatibility - describe_commands is preferred
alias define_commands describe_commands
end
module SingleTask
#Worth guarding against mix?
def task_class
@task_class ||=
begin
warn "Deprecated single task class syntax"
klass = Class.new(Task::Base)
@described.task(klass)
klass
end
end
def action(&block)
task_class.instance_eval do
define_method(:action, &block)
end
end
def undo(&block)
task_class.instance_eval do
define_method(:undo, &block)
end
end
include DSL::Argument
def embed_argument(argument)
task_class.embed_argument(argument)
end
def doesnt_undo
task_class.instance_eval do
define_method(:undo){}
end
end
def subject_methods(*names)
task_class.subject_methods(*names)
end
alias subject_method subject_methods
end
class CommandDescription
class PathHints
def initialize()
@hints = []
end
attr_reader :hints
def add(stem, root)
@hints << [stem, root]
end
def prepend(stem, root)
raise "nil stem" if stem.nil?
@hints.unshift([stem, root])
end
def merge(other)
@hints = (@hints + other.hints).uniq
end
def relocate(to_stem, with_trim)
make = self.class.new
@hints.each do |stem, root|
stem_trim = with_trim[0...stem.length]
next if stem.length >= with_trim.length and stem_trim != stem
stem = stem[stem_trim.length..-1]
root_trim = with_trim[stem.length..-1]
make.add(to_stem + stem, root_trim + root)
end
make
end
end
def self.get_caller_file
caller(0)[2].sub(/:.*/,'')
end
def self.command(name, calling_file=nil, &block)
calling_file ||= get_caller_file
return self.new(Command.new(name), calling_file, &block)
end
def self.add_to(command, path, calling_file=nil, &block)
finder = Visitors::Command.new(nil)
finder.add_state(VisitStates::CommandPath.new(command, path))
subcommand = finder.resolve.node
return CommandDescription.new(subcommand, calling_file, &block)
end
include SingleTask
def initialize(command, path = nil, stem = nil, &block)
@call_path = path || self.class.get_caller_file
@template_root = default_template_root
@path_hints = PathHints.new
@stem = stem || []
@described = command
instance_eval &block unless block.nil?
@path_hints.prepend(@stem, @template_root)
end
attr_reader :path_hints, :described
def file_set
set = Valise::Set.new
@path_hints.each do |stem, root|
search_root = Valise::SearchRoot.new(root)
if !stem.empty?
search_root = Valise::StemDecorator.new(stem, search_root)
end
set.add_search_root(search_root)
end
end
def add_to(path, &block)
finder = Visitors::Command.new(nil)
finder.add_state(VisitStates::CommandPath.new(described, path))
subcommand = finder.resolve.node
return CommandDescription.new(subcommand, &block)
end
def command(name, &block)
sub_desc = CommandDescription.new(Command.new(name), @call_path, @stem + [name], &block)
compose(sub_desc.described, nil)
end
def templates(path)
@template_root = path
end
alias templates= templates
def default_template_root
File::expand_path(@call_path, "../../templates").split(File::Separator)
end
def compose(command, path_hints)
@described.add_child(command)
@path_hints.merge(path_hints) unless path_hints.nil?
end
def merge(description, *filters)
if filters.empty?
description.described.child_commands.each do |child|
compose(child, description.path_hints.relocate(@stem + [@described.name], [child.name]))
end
else
filters.each do |filter|
child = description.described.find_command(filter)
compose(child, description.path_hints.relocate(@stem + [@described.name], filter))
end
end
end
def from_file(path, *filters)
added = []
sub_desc = CommandDescription.new(:holder, @call_path, @stem + [:holder]) do
Registry.thread_local.notify_registrations(path) do |name, description|
compose(description.described, description.path_hints)
added << name
end
end
filters = added if filters.empty
merge(sub_desc, filters)
end
def task(klass)
@described.task(klass)
end
def subject_defaults(hash)
@described.subject_defaults = hash
end
def documentation(string)
@described.doc_text = string
end
end
end
|
class FunctionCostCenter < ActiveRecord::Base
belongs_to :function
belongs_to :cost_center
end
|
module Sources
class ArsSecurity
extend CD::RssParser
def self.parse
get_feed('https://feeds.feedburner.com/arstechnica/technology-lab?format=xml') do |xml|
parse_feed(xml) do |item|
{
title: item.at('title').text,
description: CGI.escape_html(item.at('description').text.strip),
link: item.at('link').text,
comments: item.at('link').text.gsub(/click\//, ''),
updated_at: updated_at(item),
link_to_comments: item.at('link').text.gsub(/click\//, ''),
link_host: 'arstechnica.com'
}
end
end
end
private
def self.updated_at(item)
unless item.at('pubDate').nil?
DateTime.parse(item.at('pubDate').text).new_offset(0)
end
end
end
end |
class CreateParts < ActiveRecord::Migration
def change
create_table :parts do |t|
t.integer :vendor_id
t.integer :part_category_id
t.string :article
t.string :title
t.string :dimension
t.decimal :buy_price
t.decimal :margin
t.integer :sell_price
t.timestamps
end
end
end
|
require_relative 'db_connection'
require_relative 'errors'
require_relative 'exceptions'
require_relative 'core_extension'
require 'active_support/inflector'
# NB: the attr_accessor we wrote in phase 0 is NOT used in the rest
# of this project. It was only a warm up.
class SQLObject
attr_reader :errors
def self.columns
@columns ||= DBConnection.execute2(<<-SQL).first.map(&:to_sym)
SELECT
*
FROM
#{table_name}
SQL
end
def self.finalize!
columns.each do |attr_name|
define_method("#{attr_name}=") do |attr_value|
attributes[attr_name] = attr_value
end
define_method("#{attr_name}") do
attributes[attr_name]
end
end
end
def self.table_name=(table_name)
@table_name = table_name
end
def self.table_name
@table_name ||= to_s.underscore.pluralize
end
def self.all
data = DBConnection.execute2(<<-SQL).drop(1)
SELECT
#{table_name}.*
FROM
#{table_name}
SQL
parse_all(data)
end
def self.parse_all(results)
results.map do |row|
new(row)
end
end
def self.find(id)
data = DBConnection.execute2(<<-SQL, id).drop(1)
SELECT
#{table_name}.*
FROM
#{table_name}
WHERE
#{table_name}.id = ?
SQL
parse_all(data).first
end
def initialize(params = {})
@errors = Errors.new
params.each do |attr_name, attr_value|
attr_name = attr_name.to_sym
unless self.class.columns.include? attr_name
raise ArgumentError, "unknown attribute '#{attr_name}'"
end
send("#{attr_name}=", attr_value)
end
end
def attributes
@attributes ||= {}
end
def attribute_values
attributes.values
end
def save
return false unless valid?
saved? ? update : insert
end
def save!
raise RecordInvalid, errors unless valid?
saved? ? update : insert
end
def insert
cols = self.class.columns.drop(1)
col_names = cols.join(", ").delete(":")
question_marks = (%w(?) * cols.length).join(", ")
DBConnection.execute2(<<-SQL, *attribute_values)
INSERT INTO
#{self.class.table_name} (#{col_names})
VALUES
(#{question_marks})
SQL
self.id = DBConnection.last_insert_row_id
true
end
def update
cols = self.class.columns
col_names = cols.join(" = ?, ").delete(":").concat(" = ?")
DBConnection.execute2(<<-SQL, *attribute_values, id)
UPDATE
#{self.class.table_name}
SET
#{col_names}
WHERE
id = ?
SQL
true
end
def saved?
!id.nil?
end
def valid?
true
end
def invalid?
!valid?
end
end
|
require 'capistrano'
module Capistrano::Fanfare::DatabaseYaml
def self.load_into(configuration)
configuration.load do
# =========================================================================
# These are the tasks that are available to help with deploying web apps.
# You can have cap give you a summary of them with `cap -T'.
# =========================================================================
namespace :db do
desc <<-DESC
[internal] Copies database.yml from shared_path into release_path.
DESC
task :cp_database_yml, :roles => :app, :except => { :no_release => true } do
run [
"mkdir -p #{release_path}/config &&",
"cp #{shared_path}/config/database.yml #{release_path}/config/database.yml"
].join(' ')
end
end
after "deploy:update_code", "db:cp_database_yml"
end
end
end
if Capistrano::Configuration.instance
Capistrano::Fanfare::DatabaseYaml.load_into(Capistrano::Configuration.instance)
end
|
module StudioGame
class Die
# create initial state of die and call its roll method upon creation
def initialize
roll
end
# returns a random number between 1 and 6
def roll
@number = rand(1..6)
end
end
# put file-specific example code here
if __FILE__ == $0
number_rolled = Die.new
puts number_rolled
end
end
|
describe BookmarkTag do
describe '.create' do
it 'adds a BookmarkTag to the database' do
bookmark = Bookmark.create(title: 'Goal', url: 'http://www.goal.com')
tag = Tag.create(content: 'football')
bookmark_tag = BookmarkTag.create(bookmark_id: bookmark.id, tag_id: tag.id)
expect(bookmark_tag.bookmark_id).to eq(bookmark.id)
expect(bookmark_tag.tag_id).to eq(tag.id)
end
end
end |
class User < ActiveRecord::Base
has_many :feedbacks # NEW LINE - Indicates association with Micropost
belongs_to :course
before_save do |user|
user.email = email.downcase
user.remember_token = SecureRandom.urlsafe_base64
end
# End of replacement
validates :name, presence: true, length: {in: 9..30}
validates :studentID, presence: true, length: { minimum: 7 }, uniqueness: {case_sensitive: false}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: {case_sensitive: false}
validates :password, presence: true, length: { minimum: 6 }
validates :password_confirmation, presence: true
has_secure_password
def feed
Feedback.where("user_id = ?", id)
end
end
|
#
# Cookbook Name:: configure_nginx
# Recipe:: default
#
# Copyright (c) 2015 The Authors, All Rights Reserved.
default_path = "/etc/nginx/sites-enabled/default"
execute "rm -f #{default_path}" do
only_if { File.exists?(default_path) }
end
template "/etc/nginx/sites-enabled/current" do
source "nginx.conf.erb"
mode 0644
end
service "nginx" do
action :restart
end
|
#!/usr/bin/ruby
# read pianobar configuration for user email
config = File.readlines("#{ENV['XDG_CONFIG_HOME']}/pianobar/config")
begin
email = config.grep(/^\s*user/).first.split("=")[1].strip
rescue
warn "Email needs to be configured in your pianobar configuration."
exit 1
end
# pass along the email to gnome-keyring
password = `gnome-keyring-query get "pandora://#{email}/"`
if password.empty?
warn "No password, can't log in. Good bye"
exit 1
end
$stop = false
trap('INT') do
$stop = true
end
# since we're done with user-interactive stuff, we're going into the background.
Process.daemon
# and let's start pianobar!
require 'open3'
Open3.popen3("pianobar") { |stdin, stdout, stderr, wait_thr|
pid = wait_thr.pid
# stick the pid in a file, for later use by whomever.
File.open("#{ENV['XDG_CONFIG_HOME']}/pianobar/pid", "w").write(pid)
# send the password, along with an enter
stdin.puts password
stdin.close
# wait for pianobar to finish (or we're told to stop)
while wait_thr.alive? or $stop
end
wait_thr.kill
exit 0
}
|
require 'date'
class UsersController < ApplicationController
def index
@users = User.all
end
def create_user
@user = User.new
end
def login
@user = User.find_by(username: params[:username])
if @user
session[:username] = @user.id
flash[:success] = "#{ @user.username } is successfully logged in"
redirect_to root_path
else
@user = User.create(username: params[:username])
flash[:success] = "Successfully created new user #{ params[:username] } with ID #{ @user.id }"
session[:username] = @user.id
redirect_to users_path
end
end
def show
@user = User.find(params[:id])
end
def destroy
session[:user_id] = nil
flash[:notice] = 'Successfully logged out'
redirect_to root_path
end
private
def user_params
params.require(:user).permit(:name, :joined_on)
end
end
|
require 'spec_helper'
describe MessageCenter::Notification, :type => :model do
before do
@entity1 = FactoryGirl.create(:user)
@entity2 = FactoryGirl.create(:user)
@entity3 = FactoryGirl.create(:user)
end
it { is_expected.to validate_presence_of :subject }
it { is_expected.to validate_presence_of :body }
it { is_expected.to validate_length_of(:subject).is_at_most(MessageCenter.subject_max_length) }
it { is_expected.to validate_length_of(:body).is_at_most(MessageCenter.body_max_length) }
it "should notify one user" do
MessageCenter::Service.notify(@entity1, nil, "Body", "Subject")
#Check getting ALL receipts
expect(@entity1.mailbox.receipts.size).to eq(1)
receipt = @entity1.mailbox.receipts.first
notification = receipt.notification
expect(notification.subject).to eq("Subject")
expect(notification.body).to eq("Body")
#Check getting NOTIFICATION receipts only
expect(@entity1.mailbox.notifications.size).to eq(1)
notification = @entity1.mailbox.notifications.first
expect(notification.subject).to eq("Subject")
expect(notification.body).to eq("Body")
end
it "should be unread by default" do
MessageCenter::Service.notify(@entity1, nil, "Body", "Subject")
expect(@entity1.mailbox.receipts.size).to eq(1)
notification = @entity1.mailbox.receipts.first.notification
expect(notification.receipt_for(@entity1).is_unread?).to be_truthy
end
it "should be able to marked as read" do
MessageCenter::Service.notify(@entity1, nil, "Body", "Subject")
expect(@entity1.mailbox.receipts.size).to eq(1)
notification = @entity1.mailbox.receipts.first.notification
notification.mark_as_read(@entity1)
expect(notification.receipt_for(@entity1).is_read?).to be_truthy
end
it "should notify several users" do
recipients = [@entity1,@entity2,@entity3]
MessageCenter::Service.notify(recipients, nil, "Body", "Subject")
#Check getting ALL receipts
expect(@entity1.mailbox.receipts.size).to eq(1)
receipt = @entity1.mailbox.receipts.first
notification = receipt.notification
expect(notification.subject).to eq("Subject")
expect(notification.body).to eq("Body")
expect(@entity2.mailbox.receipts.size).to eq(1)
receipt = @entity2.mailbox.receipts.first
notification = receipt.notification
expect(notification.subject).to eq("Subject")
expect(notification.body).to eq("Body")
expect(@entity3.mailbox.receipts.size).to eq(1)
receipt = @entity3.mailbox.receipts.first
notification = receipt.notification
expect(notification.subject).to eq("Subject")
expect(notification.body).to eq("Body")
#Check getting NOTIFICATION receipts only
expect(@entity1.mailbox.notifications.size).to eq(1)
notification = @entity1.mailbox.notifications.first
expect(notification.subject).to eq("Subject")
expect(notification.body).to eq("Body")
expect(@entity2.mailbox.notifications.size).to eq(1)
notification = @entity2.mailbox.notifications.first
expect(notification.subject).to eq("Subject")
expect(notification.body).to eq("Body")
expect(@entity3.mailbox.notifications.size).to eq(1)
notification = @entity3.mailbox.notifications.first
expect(notification.subject).to eq("Subject")
expect(notification.body).to eq("Body")
end
it "should notify a single recipient" do
MessageCenter::Service.notify(@entity1, nil, "Body", "Subject")
#Check getting ALL receipts
expect(@entity1.mailbox.receipts.size).to eq(1)
receipt = @entity1.mailbox.receipts.first
notification = receipt.notification
expect(notification.subject).to eq("Subject")
expect(notification.body).to eq("Body")
#Check getting NOTIFICATION receipts only
expect(@entity1.mailbox.notifications.size).to eq(1)
notification = @entity1.mailbox.notifications.first
expect(notification.subject).to eq("Subject")
expect(notification.body).to eq("Body")
end
describe "scopes" do
let(:scope_user) { FactoryGirl.create(:user) }
let!(:notification) { MessageCenter::Service.notify(scope_user, nil, "Body", "Subject") }
describe ".unread" do
it "finds unread notifications" do
unread_notification = MessageCenter::Service.notify(scope_user, nil, "Body", "Subject")
notification.mark_as_read(scope_user)
expect(MessageCenter::Notification.unread.last).to eq(unread_notification)
end
end
describe ".expired" do
it "finds expired notifications" do
notification.update_attributes(expires_at: 1.day.ago)
expect(scope_user.mailbox.notifications.expired.count).to eq(1)
end
end
describe ".unexpired" do
it "finds unexpired notifications" do
notification.update_attributes(expires_at: 1.day.from_now)
expect(scope_user.mailbox.notifications.unexpired.count).to eq(1)
end
end
end
describe "#expire" do
subject { described_class.new }
describe "when the notification is already expired" do
before do
allow(subject).to receive_messages(:expired? => true)
end
it 'should not update the expires_at attribute' do
expect(subject).not_to receive :expires_at=
expect(subject).not_to receive :save
subject.expire
end
end
describe "when the notification is not expired" do
let(:now) { Time.now }
let(:one_second_ago) { now - 1.second }
before do
allow(Time).to receive_messages(:now => now)
allow(subject).to receive_messages(:expired? => false)
end
it 'should update the expires_at attribute' do
expect(subject).to receive(:expires_at=).with(one_second_ago)
subject.expire
end
it 'should not save the record' do
expect(subject).not_to receive :save
subject.expire
end
end
end
describe "#expire!" do
subject { described_class.new }
describe "when the notification is already expired" do
before do
allow(subject).to receive_messages(:expired? => true)
end
it 'should not call expire' do
expect(subject).not_to receive :expire
expect(subject).not_to receive :save
subject.expire!
end
end
describe "when the notification is not expired" do
let(:now) { Time.now }
let(:one_second_ago) { now - 1.second }
before do
allow(Time).to receive_messages(:now => now)
allow(subject).to receive_messages(:expired? => false)
end
it 'should call expire' do
expect(subject).to receive(:expire)
subject.expire!
end
it 'should save the record' do
expect(subject).to receive :save
subject.expire!
end
end
end
describe "#expired?" do
subject { described_class.new }
context "when the expiration date is in the past" do
before { allow(subject).to receive_messages(:expires_at => Time.now - 1.second) }
it 'should be expired' do
expect(subject.expired?).to be_truthy
end
end
context "when the expiration date is now" do
before {
time = Time.now
allow(Time).to receive_messages(:now => time)
allow(subject).to receive_messages(:expires_at => time)
}
it 'should not be expired' do
expect(subject.expired?).to be_falsey
end
end
context "when the expiration date is in the future" do
before { allow(subject).to receive_messages(:expires_at => Time.now + 1.second) }
it 'should not be expired' do
expect(subject.expired?).to be_falsey
end
end
context "when the expiration date is not set" do
before {allow(subject).to receive_messages(:expires_at => nil)}
it 'should not be expired' do
expect(subject.expired?).to be_falsey
end
end
end
end
|
require 'rails_helper'
RSpec.describe List, type: :model do
it{ should belong_to :user }
it{ should have_many :remarks }
it{ should have_many :confirms }
it{ should validate_presence_of :title }
it{ should validate_presence_of :body }
end |
FactoryBot.define do
factory :equipment do
equipment_name
attack_strength { Random.rand(Equipment::ATTACK_RANGE) }
defense_strength { attack_strength.zero? ? Random.rand(1..Equipment::MAX_DEFENSE) : 0 }
factory :weapon do
attack_strength { Random.rand(1..Equipment::MAX_ATTACK) }
defense_strength { 0 }
end
end
end
|
# frozen_string_literal: true
FactoryBot.define do
factory :property do
sequence(:property_name) { |i| "Some Property Name #{i}" }
property_address { 'Some Property Address' }
landlord_first_name { 'Some Landlord Address' }
landlord_last_name { 'Some Landlord Last Name' }
sequence(:landlord_email) { |i| "somelandlordemail#{i}@topfloor.ie" }
end
end
|
class StoriesController < ApplicationController
before_action :get_root, :get_story
@root
def show
end
def get_story
@story = @root.get_story(params[:id])
@story_characters = @root.get_story_characters(@story.first["id"])
end
def get_root
@root ||= Root.new
end
end
|
class TextblocksController < ApplicationController
before_filter :login_required, :except => [ :show, :short, :frontpage ]
def index
list
render :action => 'list'
end
def list
@textblock_pages, @textblocks = paginate :textblocks, :per_page => 25
end
def search
if !params['criteria'] || 0 == params['criteria'].length
@items = nil
render :layout => false
else
@items = Textblock.find(:all, :order => 'updated_at DESC',
:conditions => [ 'LOWER(title) OR LOWER(content) LIKE ?',
'%' + params['criteria'].downcase + '%' ])
@mark_term = params['criteria']
render :layout => false
end
end
def show
@textblock = Textblock.find(params[:id])
if params[:simple_layout]
render :layout => 'simple'
else
render :layout => false
end
end
def flashpreview
@textblock = Textblock.find(params[:id])
end
def short
@textblock = Textblock.find_by_id(params[:block_id])
render :layout => false
end
def frontpage
@blocks = Textblock.find_all_by_title("frontpage")
render :layout => false
end
def new
@textblock = Textblock.new
end
def create
@textblock = Textblock.new(params[:textblock])
if @textblock.save
@textblock.block_links.create(params[:block_link])
flash[:ok] = 'Textblock was successfully created.'
redirect_to :controller=>"block_links", :action => "close_reload"
else
flash[:error] = 'Unable to create Textblock.'
render :action => 'new'
end
end
def edit
@textblock = Textblock.find(params[:id])
render :layout => 'simple'
end
def update
@textblock = Textblock.find(params[:id])
if @textblock.update_attributes(params[:textblock])
flash[:ok] = 'Textblock was successfully updated.'
#redirect_to :action => 'show', :id => @textblock
redirect_to :controller=>"/block_links", :action => "close_reload"
else
render :layout => 'simple'
render :action => 'edit'
end
end
def destroy
Textblock.find(params[:id]).destroy
if session[:current_article]
redirect_to :controller => '/articles', :action => 'edit', :id => session[:current_article]
elsif session[:current_collection]
redirect_to :controller => '/collections', :action => 'edit', :id => session[:current_collection]
else
redirect_to :action => 'list'
end
end
def destroylink
BlockLink.find(params[:id]).destroy
if session[:current_article]
redirect_to :controller => '/articles', :action => 'edit', :id => session[:current_article]
elsif session[:current_collection]
redirect_to :controller => '/collections', :action => 'edit', :id => session[:current_collection]
else
redirect_to :action => 'list'
end
end
end
|
require_relative "#{App.root}/app/models/color.rb"
require_relative "#{App.root}/app/models/substance.rb"
class TestKit < Dry::Struct
attribute :name, Types::Strict::String
attribute :color, Types.Instance(Color)
end
|
#This application runs in order to convert the IRDS dashboard data from csv to xls
class CSVConverter
require 'csv'
require 'spreadsheet'
require 'sudo'
def initialize
p "Initialize converter..."
@counter = 0
read_write_save_file
end
def read_write_save_file
p "Createing New Spreadsheet"
book = Spreadsheet::Workbook.new
sheet = book.create_worksheet :name => 'dashboard'
p "Reading CSV and writing to new spreadsheet..."
file_path = "/media/qadprod/dashboard.csv"
CSV.foreach(file_path, col_sep: ",", headers: true) do |row|
if @counter == 0
sheet.row(0).concat row.headers
else
column_counter = 0
row.each do |r|
sheet[@counter,column_counter] = r[1]
column_counter += 1
end
end
@counter += 1
end
book.write '/home/itadmin/apps/ruby/csvConverter/dashboard.xls'
end
end
CSVConverter.new
|
require 'test_helper'
describe ShallowAttributes::Type::DateTime do
let(:type) { ShallowAttributes::Type::DateTime.new }
describe '#coerce' do
describe 'when value is DateTime' do
it 'returns date time object' do
time = DateTime.now
type.coerce(time).must_equal time
end
end
describe 'when value is Time' do
it 'returns date time object' do
time = Time.now
type.coerce(time).class.must_equal DateTime
end
end
describe 'when value is String' do
it 'returns date time object' do
type.coerce('Thu Nov 29 14:33:20 GMT 2001').to_s.must_equal '2001-11-29T14:33:20+00:00'
end
end
describe 'when value is invalid String' do
it 'returns error' do
err = -> { type.coerce('') }.must_raise ShallowAttributes::Type::InvalidValueError
err.message.must_equal %(Invalid value "" for type "DateTime")
err = -> { type.coerce('1') }.must_raise ShallowAttributes::Type::InvalidValueError
err.message.must_equal %(Invalid value "1" for type "DateTime")
end
end
describe 'when value is Numeric' do
it 'returns InvalidValueError' do
err = -> { type.coerce(123123123) }.must_raise ShallowAttributes::Type::InvalidValueError
err.message.must_equal %(Invalid value "123123123" for type "DateTime")
end
end
describe 'when value is Nil' do
it 'returns InvalidValueError' do
err = -> { type.coerce(nil) }.must_raise ShallowAttributes::Type::InvalidValueError
err.message.must_equal %(Invalid value "" for type "DateTime")
end
end
describe 'when value is TrueClass' do
it 'returns InvalidValueError' do
err = -> { type.coerce(true) }.must_raise ShallowAttributes::Type::InvalidValueError
err.message.must_equal %(Invalid value "true" for type "DateTime")
end
end
describe 'when value is FalseClass' do
it 'returns InvalidValueError' do
err = -> { type.coerce(false) }.must_raise ShallowAttributes::Type::InvalidValueError
err.message.must_equal %(Invalid value "false" for type "DateTime")
end
end
describe 'when value is not allowed' do
it 'returns error' do
err = -> { type.coerce([]) }.must_raise ShallowAttributes::Type::InvalidValueError
err.message.must_equal %(Invalid value "[]" for type "DateTime")
err = -> { type.coerce({}) }.must_raise ShallowAttributes::Type::InvalidValueError
err.message.must_equal %(Invalid value "{}" for type "DateTime")
err = -> { type.coerce(:'1') }.must_raise ShallowAttributes::Type::InvalidValueError
err.message.must_equal %(Invalid value "1" for type "DateTime")
err = -> { type.coerce(Class) }.must_raise ShallowAttributes::Type::InvalidValueError
err.message.must_equal %(Invalid value "Class" for type "DateTime")
err = -> { type.coerce(Class.new) }.must_raise ShallowAttributes::Type::InvalidValueError
err.message.must_match 'Invalid value "#<Class:'
err.message.must_match '" for type "DateTime"'
end
end
end
end
|
require 'helper'
require 'deviantart'
require 'deviantart/authorization_code'
require 'deviantart/authorization_code/refresh_token'
require 'deviantart/client_credentials/access_token'
class DeviantArt::Client::Test < Test::Unit::TestCase
sub_test_case '#refresh_access_token with Authorization Code Grant' do
setup do
@da, @credentials = create_da
@refresh_authorization_code = fixture('refresh_authorization_code.json')
stub_da_request(
method: :post,
url: "https://#{DeviantArt::Client.default_host}/oauth2/token",
status_code: 200,
body: @refresh_authorization_code)
end
test 'requests the correct resource' do
@da.access_token = nil
assert_nil(@da.access_token)
resp = @da.refresh_access_token
assert(!@da.access_token.nil?)
assert_instance_of(DeviantArt::AuthorizationCode::RefreshToken, resp)
assert_equal('Bearer', resp.token_type)
assert_equal(3600, resp.expires_in)
assert_equal('success', resp.status)
end
end
sub_test_case '#on_refresh_access_token and #on_refresh_authorization_code with Authorization Code Grant' do
setup do
@da, @credentials = create_da
@refresh_authorization_code = fixture('refresh_authorization_code.json')
stub_da_request(
method: :post,
url: "https://#{DeviantArt::Client.default_host}/oauth2/token",
status_code: 200,
body: @refresh_authorization_code)
end
test 'requests the correct resource' do
@da.access_token = nil
@da.on_refresh_access_token do |access_token|
assert_instance_of(String, access_token)
end
@da.on_refresh_authorization_code do |access_token, refresh_token|
assert_instance_of(String, access_token)
assert_instance_of(String, refresh_token)
end
@da.refresh_access_token
end
end
sub_test_case '#refresh_access_token with Client Credentials Grant' do
setup do
credentials_input = fixture('credentials-input.json')
@da = DeviantArt::Client.new do |config|
config.client_id = credentials_input.json['client_credentials']['client_id']
config.client_secret = credentials_input.json['client_credentials']['client_secret']
config.grant_type = :client_credentials
config.access_token_auto_refresh = true
end
@refresh_client_credentials = fixture('refresh_client_credentials.json')
stub_da_request(
method: :post,
url: "https://#{DeviantArt::Client.default_host}/oauth2/token",
status_code: 200,
body: @refresh_client_credentials)
end
test 'requests the correct resource' do
@da.access_token = nil
assert_nil(@da.access_token)
resp = @da.refresh_access_token
assert(!@da.access_token.nil?)
assert_instance_of(DeviantArt::ClientCredentials::AccessToken, resp)
assert_equal('Bearer', resp.token_type)
assert_equal(3600, resp.expires_in)
assert_equal('success', resp.status)
end
end
sub_test_case '#on_refresh_access_token with Client Credentials Grant' do
setup do
credentials_input = fixture('credentials-input.json')
@da = DeviantArt::Client.new do |config|
config.client_id = credentials_input.json['client_credentials']['client_id']
config.client_secret = credentials_input.json['client_credentials']['client_secret']
config.grant_type = :client_credentials
config.access_token_auto_refresh = true
end
@refresh_client_credentials = fixture('refresh_client_credentials.json')
stub_da_request(
method: :post,
url: "https://#{DeviantArt::Client.default_host}/oauth2/token",
status_code: 200,
body: @refresh_client_credentials)
end
test 'requests the correct resource' do
@da.access_token = nil
@da.on_refresh_access_token do |access_token|
assert_instance_of(String, access_token)
end
@da.refresh_access_token
end
end
end
|
class ItemsController < ApplicationController
def index
@items = Item.all
end
def show
@item = Item.find(params[:id])
end
def new
@item = Item.new
end
def create
@item = Item.create(item_params)
@item.save
redirect_to @item
end
private
def item_params
params.require(:item).permit(:name, :description, :price, :artist, :imgurl)
end
end
|
require 'spec_helper'
describe MassMigrator do
subject { MassMigrator.new(/^mentions_client_3$/, :db => $db) }
def table_columns(table_name)
$db.schema(table_name, :reload => true).map {|(column, data)| column }
end
let!(:migration_class) do
Class.new(MassMigrator::Migration) do
def up
add_column table_name, :created_at, DateTime
end
def down
drop_column table_name, :created_at
end
def self.name
"AddCreatedAt"
end
end
end
before(:each) do
$db.create_table!(:mentions_client_3) { primary_key :id }
$db.drop_table(:mm_schema_info) if $db.table_exists?(:mm_schema_info)
end
it "initializes schema info table unless it exists" do
$db.drop_table(:mm_schema_info) if $db.table_exists?(:mm_schema_info)
subject
$db.tables.should include(:mm_schema_info)
end
it "doesn't recreate schema info table if it exists" do
$db.create_table!(:mm_schema_info) { primary_key :id }
$db[:mm_schema_info] << {}
subject
$db.tables.should include(:mm_schema_info)
$db[:mm_schema_info].count.should > 0
end
it "instantiates migrations" do
migration = subject.migrations.detect {|m| m.table_name == :mentions_client_3 && m.name.should == "AddCreatedAt" }
migration.should_not be_nil
migration.should be_pending
end
it "runs migrations" do
subject.run_pending_migrations
described_class.new(/^mentions_client_3$/, :db => $db).pending_migrations.should be_empty
table_columns(:mentions_client_3).should include(:created_at)
end
it "creates records about run migrations" do
subject.run_pending_migrations
migration_record = $db[:mm_schema_info].
filter(:table_name => 'mentions_client_3',
:migration_name => 'AddCreatedAt').
first
migration_record.should_not be_nil
end
it "preloads migrations from given path" do
MassMigrator::Migration.list.clear
migrator = MassMigrator.new(/^mentions_client_3$/, :db => $db, :migrations => "spec/fixtures/migrations")
migrator.migrations.size.should > 0
end
it "can revert migrations" do
subject.run_pending_migrations
table_columns(:mentions_client_3).should include(:created_at)
subject.revert_migrations("AddCreatedAt")
table_columns(:mentions_client_3).should_not include(:created_at)
end
it "removes records from schema info table upon reverting" do
subject.run_pending_migrations
$db[:mm_schema_info].filter(:table_name => 'mentions_client_3',
:migration_name => 'AddCreatedAt').
first.should_not be_nil
subject.revert_migrations("AddCreatedAt")
$db[:mm_schema_info].filter(:table_name => 'mentions_client_3',
:migration_name => 'AddCreatedAt').
first.should be_nil
end
end
|
# frozen_string_literal: true
module Mutations
class UpdateMe < ::Mutations::BaseMutation
description 'カレントユーザー情報更新'
argument :name, ::String, required: false
field :current_user, ::Types::Objects::CurrentUserObject, null: true
def mutate(name:)
context[:current_info][:user].update!(name: name)
{
current_user: context[:current_info][:user].reload
}
end
end
end
|
class Baraja
attr_reader :cartas
def initialize(*cartas)
@cartas = *cartas
end
def numero_de_cartas
@cartas.length
end
def contiene_carta?(c)
@cartas.include?(c)
end
def add_carta(c)
@cartas += [ c ]
end
def self.completa
mazo = []
Carta.palos.each do |palo|
(1..12).each do |valor|
mazo += [ Carta.new(palo, valor) ]
end
end
Baraja.new(*mazo)
end
def to_s
s = ""
@cartas.each do |carta|
s += "#{carta.to_s}\n"
end
s[0..-2]
end
def ordenada
Baraja.new(*(@cartas.sort))
end
def barajada
Baraja.new(*(@cartas.shuffle))
end
end
|
require 'delegate'
require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/object/blank'
require 'active_model/naming'
require 'hydramata/works/conversions/translation_key_fragment'
require 'hydramata/works/conversions/presenter'
module Hydramata
module Works
# Responsible for wrapping a given Work such that it can interact with
# form rendering in HTML as well as exposing validation behavior.
class WorkForm < SimpleDelegator
include Conversions
def initialize(work, collaborators = {})
self.work = (work)
@errors = collaborators.fetch(:error_container) { default_error_container }
@validation_service = collaborators.fetch(:validation_service) { default_validation_service }
@renderer = collaborators.fetch(:renderer) { default_renderer }
yield(self) if block_given?
end
attr_reader :errors
attr_reader :validation_service, :renderer
private :validation_service, :renderer
def render(options = {})
renderer.call(options)
end
def valid?
validate
errors.size == 0
end
def to_key
persisted? ? [identity] : nil
end
def to_param
persisted? ? identity : nil
end
def to_partial_path
# @TODO - need to figure out what this should be
''
end
def persisted?
identity.present?
end
def new_record?
! persisted?
end
# Needed for Validator interaction
def self.human_attribute_name(attr, options = {})
attr
end
def self.model_name
# @TODO - allow overwrite of the ActiveModel::Name, which may require
# overwriting #class to be something else.
@_model_name ||= ActiveModel::Name.new(self, Hydramata::Works, explicit_model_name)
end
def self.explicit_model_name
Hydramata.configuration.work_model_name rescue nil
end
private_class_method :explicit_model_name
# Needed for Validator interaction
def read_attribute_for_validation(attribute_name)
send(TranslationKeyFragment(attribute_name))
end
def inspect
format('#<%s:%#0x work=%s>', WorkForm, __id__, __getobj__.inspect)
end
def instance_of?(klass)
super || __getobj__.instance_of?(klass)
end
def form_options
@form_options ||= {}
end
def form_options=(options)
@form_options = options
end
protected
def work=(object)
__setobj__(Presenter(object))
end
private
def respond_to_missing?(method_name, include_all = false)
super || __getobj__.has_property?(method_name)
end
def method_missing(method_name, *args, &block)
if __getobj__.has_property?(method_name)
# @TODO - The Law of Demeter is being violated.
__getobj__.properties.fetch(method_name).values
else
super
end
end
def default_error_container
require 'active_model/errors'
ActiveModel::Errors.new(self)
end
def default_validation_service
require 'hydramata/works/validation_service'
ValidationService
end
def validate
validation_service.call(self)
end
def default_renderer
require 'hydramata/works/work_template_renderer'
WorkTemplateRenderer.new(self)
end
end
end
end
|
class AppointmentRequestMailer < ApplicationMailer
default from: 'community.cares.boulder@gmail.com'
def appointment_request_confirmation_email(appointment_request)
@appointment_request = appointment_request
#@url = 'https://community-cares-iansharp93.c9.io/appointment_request'
mail(to: [@appointment_request.email, 'community.cares.boulder@gmail.com'], subject: 'Welcome to Community Cares!')
end
def appointment_request_internal_email(appointment_request)
@appointment_request = appointment_request
mail(to: 'community.cares.boulder@gmail.com', subject: 'Client Appointment Request')
end
end
|
require './test_helper'
require './lib/sales_engine'
require './lib/transaction_repository'
require 'bigdecimal'
class TransactionRepositoryTest < MiniTest::Test
def setup
se = SalesEngine.from_csv({
:items => "./data/mock.csv",
:merchants => "./data/mock.csv",
:invoices => "./data/mock.csv",
:invoice_items => "./data/mock.csv",
:transactions => "./data/transactions.csv",
:customers => "./data/mock.csv"})
@tr = se.transactions
@transaction = @tr.find_by_id(2)
end
def test_find_transaction_by_id
found_transaction = @tr.find_by_id(2)
assert_equal 2, found_transaction.id
assert_instance_of Transaction, found_transaction
end
def test_it_can_find_all_by_invoice_id
assert_equal 2, @tr.find_all_by_invoice_id(2179).length
assert_equal 2179, @tr.find_all_by_invoice_id(2179).first.invoice_id
assert_instance_of Transaction, @tr.find_all_by_invoice_id(2179).first
assert @tr.find_all_by_invoice_id(14560).empty?
end
def test_find_all_by_credit_card_number
assert_equal 1, @tr.find_all_by_credit_card_number('4848466917766329').length
assert_instance_of Transaction, @tr.find_all_by_credit_card_number('4848466917766329').first
assert @tr.find_all_by_credit_card_number('4848466917766328').empty?
end
def test_find_all_by_result
assert_equal 4158, @tr.find_all_by_result(:success).length
assert_instance_of Transaction, @tr.find_all_by_result(:success).first
assert_equal 827, @tr.find_all_by_result(:failed).length
assert_instance_of Transaction, @tr.find_all_by_result(:failed).first
end
def test_it_can_create_new_transaction_instance
attributes = {
:invoice_id => 8,
:credit_card_number => "4242424242424242",
:credit_card_expiration_date => "0220",
:result => "success",
:created_at => Time.now,
:updated_at => Time.now}
@tr.create(attributes)
new_transaction = @tr.find_by_id(4986)
assert_equal 8, new_transaction.invoice_id
end
def test_it_can_update_transaction
attributes = {
:invoice_id => 8,
:credit_card_number => "4242424242424242",
:credit_card_expiration_date => "0220",
:result => "success",
:created_at => Time.now,
:updated_at => Time.now}
@tr.create(attributes)
new_attributes = {result: :failed}
@tr.update(4986, new_attributes)
assert_equal :failed, @tr.find_by_id(4986).result
assert_equal '0220', @tr.find_by_id(4986).credit_card_expiration_date
assert @tr.find_by_id(4986).created_at < @tr.find_by_id(4986).updated_at
end
def test_it_cant_update_transaction_id_invoice_id_created_at
attributes = {
:invoice_id => 8,
:credit_card_number => "4242424242424242",
:credit_card_expiration_date => "0220",
:result => "success",
:created_at => Time.now,
:updated_at => Time.now}
@tr.create(attributes)
new_attributes = {
id: 5000,
invoice_id: 2,
created_at: Time.now}
@tr.update(4986, new_attributes)
assert_nil @tr.find_by_id(5000)
refute_equal 2, @tr.find_by_id(4986).invoice_id
refute_equal Time.now, @tr.find_by_id(4986).created_at
end
def test_it_can_delete_transaction
attributes = {
:invoice_id => 8,
:credit_card_number => "4242424242424242",
:credit_card_expiration_date => "0220",
:result => "success",
:created_at => Time.now,
:updated_at => Time.now}
@tr.create(attributes)
assert_instance_of Transaction, @tr.find_by_id(4986)
@tr.delete(4986)
assert_nil @tr.find_by_id(4986)
end
def test_it_returns_nil_if_you_try_to_delete_nonexistant_ivoice_item
assert_nil @tr.delete(5000)
end
end
|
require 'rails_helper'
RSpec.describe CheckinsHelper, type: :helper do
describe '#date_labels' do
it 'returns last 10 days' do
expect(helper.date_labels.count).to eq 10
expect(helper.date_labels.last).to eq Date.today.strftime(DATE_FORMAT)
end
end
describe '#checkin_times' do
let(:hour_in_float) { 11.11 }
before do
allow(helper).to receive(:get_checkin_hour_of_date).and_return(hour_in_float)
end
it 'returns array of checkin hour' do
expect(helper.checkin_times(Checkin.all)).to eq [hour_in_float] * 10
end
end
describe '#get_checkin_hour_of_date' do
let(:created_at) { Time.now }
let(:response) { helper.get_checkin_hour_of_date(Checkin.all, created_at) }
context 'no checkin in the date' do
it 'returns 0' do
expect(response).to eq 0
end
end
context 'has checkin in the date' do
let!(:checkin) { create(:checkin, created_at: created_at) }
let(:hour_in_float) { 22.22 }
before do
allow_any_instance_of(Checkin).to receive(:get_hour_in_float).and_return(hour_in_float)
end
it 'returns hour of checkin' do
expect(response).to eq hour_in_float
end
end
end
end
|
#!/usr/bin/env ruby
require 'csv'
require 'awesome_print'
require 'json'
class Splitter
def initialize(source, target, key)
@source = source
@target = target
@key = key
values = readCSV(@source)
splitted = values.group_by do |item|
item[key]
end
ap splitted
splitted.each do |key, items|
writeCSV("#{@target}-#{key}", items)
end
# writeCSV(@target, values)
end
end
def readCSV (file)
CSV.read("target/#{file}.csv", { encoding: "UTF-8", headers: true, header_converters: :symbol, converters: :all }).map { |d| d.to_hash }
end
def writeCSV (file, hash)
CSV.open("target/#{file}.csv", "w") do |row|
row << hash.first.keys
hash.each { |obj| row << obj.values }
end
end
people = Splitter.new(
'table_people-carto',
'table_people-split',
:topic
) |
require 'spec_helper'
describe DataLink do
let(:user) { User.make! }
context "DataLink creation" do
before(:all) do
@deployment = given_resources_for([:deployment], :user => user)[:deployment]
end
it "should be invalid without a user, deployment and sourcable" do
data_link = DataLink.new()
data_link.should have(1).error_on(:user_id)
data_link.should have(1).error_on(:deployment_id)
# Sourcable is equal to Targetable at this point and therefore the following error should occur
data_link.should have(1).error_on(:sourcable)
data_link.errors.count.should == 3
data_link.should_not be_valid
end
it "should be invalid if sourcable/targetable is in different deployment" do
data_link = @deployment.data_links.first
data_link.sourcable = given_resources_for([:server], :user => user)[:server]
data_link.should_not be_valid
data_link.should have(1).error_on(:sourcable)
data_link.errors.count.should == 1
end
it "should be invalid if sourcable and targetable are the same" do
data_link = @deployment.data_links.first
data_link.sourcable = data_link.targetable
data_link.should_not be_valid
data_link.should have(1).error_on(:sourcable)
data_link.errors.count.should == 1
end
it "should return correct string for best_in_place" do
data_link = @deployment.data_links.first
data_link.sourcable_type_id.should == "#{data_link.sourcable_type}:#{data_link.sourcable_id}"
data_link.targetable_type_id.should == "#{data_link.targetable_type}:#{data_link.targetable_id}"
end
end
it "should be deep cloned" do
cloud_provider = CloudProvider.make!
cloud = Cloud.make!(:name => 'TestCloud', :cloud_provider => cloud_provider)
data_link = DataLink.make(:user => user)
deployment = Deployment.make!(:user => user)
data_link.deployment = deployment
# Create first server
server1 = Server.make(:user => user)
server1.deployment = deployment
server1.server_type = ServerType.make!
server1.cloud = cloud
server1.save
# Create second server
server2 = Server.make(:user => user)
server2.deployment = deployment
server2.server_type = ServerType.make!
server2.cloud = cloud
server2.save
data_link.sourcable = server1
data_link.targetable = server2
data_link.save
new_data_link = data_link.deep_clone
new_data_link.should be_valid
new_data_link.name.should == "Copy of #{data_link.name}"
new_data_link.user.should == data_link.user
new_data_link.deployment.should == data_link.deployment
new_data_link.sourcable.should == data_link.sourcable
new_data_link.targetable.should == data_link.targetable
end
end |
require 'snippetize/version'
require 'snippetize/snippet'
require 'snippetize/action_view_extensions/snippetize_helper'
module Snippetize
mattr_accessor :location
@@location = 'snippets'
def self.setup
yield self
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 bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
if Rails.env.development?
products = 3.times.inject([]) do |memo|
memo << { name: Faker::Commerce.product_name, price: (rand 10000)/100.0 }
end
ActiveRecord::Base.transaction do
# Product.destroy_all
Product.create! products
end
end |
# encoding: utf-8
# Inspec test for recipe jnj_chef_stack::workflow_builder
# The Inspec reference, with examples and extensive documentation, can be
# found at https://docs.chef.io/inspec_reference.html
packages = %w(chefdk)
packages.each do |p|
describe package(p) do
it { should be_installed }
end
end
dirs = %w(.chef bin lib etc)
dirs.each do |d|
describe directory("/var/opt/delivery/workspace/#{d}") do
it { should exist }
end
end
|
module RubyKongAuth
class Model
def initialize(attributes)
attributes.each do |key, value|
send("#{key.to_s}=", value) rescue false
end
end
def instance_values
Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }]
end
def to_sym
self.instance_values.symbolize_keys!
end
# check that the attributes specified in args exist and is not nil
def requires(*args)
missing = missing_attributes(args)
if missing.length == 1
raise(ArgumentError, "#{missing.first} is required for this operation")
elsif missing.any?
raise(ArgumentError, "#{missing[0...-1].join(", ")} and #{missing[-1]} are required for this operation")
end
end
def requires_one(*args)
missing = missing_attributes(args)
return unless missing.length == args.length
raise(ArgumentError, "#{missing[0...-1].join(", ")} or #{missing[-1]} are required for this operation")
end
def requires_only(*args)
missing = missing_attributes(args)
return if missing.length == (args.length - 1)
raise(ArgumentError, "Only support one in #{args[0...-1].join(", ")} and #{args[-1]}")
end
def self.symbolize_keys!(h)
Hash[h.map{|(k,v)| [k.to_sym,v]}]
end
def as_json
self.instance_values
end
protected
def missing_attributes(args)
missing = []
args.each do |arg|
missing << arg unless send("#{arg}")
end
missing
end
end
end
|
class Vehicle < ActiveRecord::Base
belongs_to :customer
before_save { self.vehicle_no =vehicle_no.upcase}
validates :vehicle_no, uniqueness: { case_sensitive: false}
validates_format_of :vehicle_no, :with => /\A^[A-Za-z]{2}[a-zA-Z0-9]{3,}$\z/, messages: "Invalid Vehcile Number format"
validates :Model_name, presence: true, length: {minimum:3, maximum:10}
validates :customer_id, presence: true
end |
module Spree
class TemplateText < ActiveRecord::Base
validates_presence_of :name
attr_accessible :name, :body
#for resource_class.resourceful
scope :resourceful, ->(theme){ where("1=1") }
default_scope ->{ where(:site_id=>Site.current.id)}
end
end |
module Fog
module Compute
class Google
##
# Represents a Region resource
#
# @see https://developers.google.com/compute/docs/reference/latest/regions
class Region < Fog::Model
identity :name
attribute :kind
attribute :id
attribute :creation_timestamp, :aliases => "creationTimestamp"
attribute :deprecated
attribute :description
attribute :quotas
attribute :self_link, :aliases => "selfLink"
attribute :status
attribute :zones
DOWN_STATE = "DOWN".freeze
UP_STATE = "UP".freeze
def up?
status == UP_STATE
end
end
end
end
end
|
#rake db:test:prepare
Given /^I am on the "([^"]*) ([^"]*)" page$/ do |action,controller|
visit("/#{controller.downcase}s/#{action.downcase}")
end
When /^I submit a purchase called "([^"]*)" that costs "([^"]*)"$/ do |purchase,cost|
fill_in 'Purchase', :with => purchase
fill_in 'Cost', :with => cost
click_button "Create Purchase"
end
Then /^a purchase called "([^"]*)" that costs "([^"]*)" should be saved$/ do |purchase,cost|
Purchase.find(:first, :conditions => "name = '#{purchase}' AND cost = #{cost.to_f}").name.should == "Anything"
end
And /^I enter a \$(\d+) purchase$/ do |cost|
fill_in 'Cost', :with => cost.to_s
end
And /^I name my purchase "([^"]*)"$/ do |name|
fill_in 'Purchase', :with => name
end
Then /^I submit the (.*) form$/ do |model|
click_button "Create #{model}"
end
#Then /^the object should not be saved$/ do
#puts page.body
#end
Then /^an error reading "([^"]*)" should be displayed$/ do |error|
page.body.should include error
end
Given /^an error reading "([^"]*)" should be displayed on the (.*) field$/ do |error, field|
field = field.downcase.gsub(' ', '_')
error_list = all("#id_#{field}_errors li").map {|e| e.text }
error_list.should include error
end
Given /^there should be exactly (\d+) errors? displayed on the (.*) field$/ do |error_count, field|
error_count = error_count.to_i
field = field.downcase.gsub(' ', '_')
error_list = all("#id_#{field}_errors li").map {|e| e.text }
error_list.length.should == error_count
end
Given /^an error reading "([^"]*)" should be displayed on the main error list$/ do |error|
error_list = all(".form_errors li").map {|e| e.text }
error_list.should include error
end
Given /^there should be exactly (\d+) errors? displayed on the main error list$/ do |error_count|
error_count = error_count.to_i
error_list = all(".form_errors li").map {|e| e.text }
error_list.length.should == error_count
end
|
# frozen_string_literal: true
module Relax
module SVG
module Structural
# Structural element as defined by
# https://www.w3.org/TR/SVG2/struct.html#GElement
class Group < Relax::SVG::Structural::StructuralPrototype
NAME = 'g'
GEOMETRY_ATTRIBUTES = %i[x y width height].freeze
SPECIFIC_ATTRIBUTES = [:transform].freeze
ATTRIBUTES = (
GEOMETRY_ATTRIBUTES +
SPECIFIC_ATTRIBUTES +
Relax::SVG::Structural::ATTRIBUTES
).freeze
attr_accessor(*ATTRIBUTES)
end
end
end
end
|
require 'rails_helper'
RSpec.shared_examples_for Contact do
describe '#prepares_for_form' do
it 'prepares address' do
contactable = described_class.new
expect(contactable.address).to be_nil
contactable.prepare_for_form
expect(contactable.address).not_to be_nil
end
it '#clear_up_form destroys address' do
contactable = described_class.new
contactable.prepare_for_form
contactable.clear_up_form
expect(contactable.address).not_to be_nil
end
end
end
RSpec.describe Property do
it_behaves_like Contact
end
RSpec.describe Agent do
it_behaves_like Contact
end
RSpec.describe Client do
it_behaves_like Contact
end
|
##
# Copyright 2017-2018 Bryan T. Meyers
#
# 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.
##
require 'test/unit'
require_relative('../../../lib/wiki-that')
class ListGenTest < Test::Unit::TestCase
def test_empty
gen = WikiThat::HTMLGenerator.new('', 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('', gen.result, 'Nothing should have been generated')
end
def test_ul
gen = WikiThat::HTMLGenerator.new('*', 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<ul><li></li></ul>', gen.result, 'Unordered List should have been generated')
end
def test_ul_li
gen = WikiThat::HTMLGenerator.new('*A', 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<ul><li>A</li></ul>', gen.result, 'Unordered List should have been generated')
end
def test_ul_li2
gen = WikiThat::HTMLGenerator.new('* ABC', 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<ul><li> ABC</li></ul>', gen.result, 'Unordered List should have been generated')
end
def test_ol
gen = WikiThat::HTMLGenerator.new('#', 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<ol><li></li></ol>', gen.result, 'Unordered List should have been generated')
end
def test_ol_li
gen = WikiThat::HTMLGenerator.new('#A', 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<ol><li>A</li></ol>', gen.result, 'Unordered List should have been generated')
end
def test_ol_li2
gen = WikiThat::HTMLGenerator.new('# ABC', 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<ol><li> ABC</li></ol>', gen.result, 'Unordered List should have been generated')
end
def test_ol_ul
gen = WikiThat::HTMLGenerator.new('#* ABC', 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<ol><li><br><ul><li> ABC</li></ul></li></ol>', gen.result, 'Unordered List should have been generated')
end
def test_ul_ol_ul
gen = WikiThat::HTMLGenerator.new("*# AB\n*#* ABC", 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<ul><li><br><ol><li> AB<ul><li> ABC</li></ul></li></ol></li></ul>', gen.result, 'Unordered List should have been generated')
end
def test_dl
gen = WikiThat::HTMLGenerator.new(': ABC', 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<dl><dd> ABC</dd></dl>', gen.result, 'Unordered List should have been generated')
end
def test_dl2
gen = WikiThat::HTMLGenerator.new('; ABC', 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<dl><dt> ABC</dt></dl>', gen.result, 'Unordered List should have been generated')
end
def test_dl_dt_dn
gen = WikiThat::HTMLGenerator.new("; ABC\n: DEF", 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<dl><dt> ABC</dt><dd> DEF</dd></dl>', gen.result, 'Unordered List should have been generated')
end
def test_dl_dn_dt
gen = WikiThat::HTMLGenerator.new(": ABC\n; DEF", 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<dl><dd> ABC</dd><dt> DEF</dt></dl>', gen.result, 'Unordered List should have been generated')
end
def test_ol_dl_dt_dn
gen = WikiThat::HTMLGenerator.new("#; ABC\n#: DEF", 'wiki', 'BOB', 'sub/folder', 'media/folder')
gen.generate
assert_equal('<ol><li><br><dl><dt> ABC</dt><dd> DEF</dd></dl></li></ol>', gen.result, 'Unordered List should have been generated')
end
end
|
class StoriesController < ApplicationController
include ChapterExtension
include AdventurerExtension
# before_filter :authenticate_user!, except: [:prelude, :read, :search, :index]
# load_and_authorize_resource except: [:prelude, :read]
before_filter :authenticate_user!, except: [:search_result, :detail]
load_and_authorize_resource except: [:search_result, :favorite, :detail]
# GET /stories
# GET /stories.json
def index
@stories = Story.by_user(current_user.id).page(params[:page]).per(5)
end
# GET /stories/1
# GET /stories/1.json
def show
@story = Story.find(params[:id])
@items = @story.items
@chapters = @story.chapters.includes(:decisions)
end
def detail
@story = Story.find(params[:story_id])
end
def prelude
@story = Story.find(params[:story_id])
if @story.published || @story.user == current_user
@adventurer = Adventurer.by_user_and_story(current_user, @story).first
if params[:new_story]
@adventurer = Adventurer.clear_or_create_adventurer(@adventurer, params[:story_id])
else
redirect_to story_read_path(@story, continue: true, chapter_id: @adventurer.chapter.id, adventurer_id: @adventurer.id)
end
else
redirect_to root_url, alert: I18n.t('actions.not_published')
end
end
def read
@story = Story.find_by(slug: params[:story_id])
if @story.try(:published) || @story.try(:user) == current_user
if params[:continue]
@chapter = Chapter.find(params[:chapter_id])
@adventurer = Adventurer.find(params[:adventurer_id])
@adventurers_items = AdventurerItem.by_adventurer(@adventurer)
else
@chapter = @story.chapters.find_by reference: params[:reference]
if @story && @story.has_adventurer?(current_user.adventurers) && @chapter.present?
set_gold_items_and_attributes(current_user)
this_decision = Decision.find_by(destiny_num: @chapter.id)
@adventurer.use_required_item(this_decision)
else
redirect_to root_url, alert: I18n.t('actions.not_found')
end
end
else
redirect_to root_url, alert: I18n.t('actions.not_published')
end
end
def search_result
@stories = Story.search(params[:search]).published.page(params[:page]).per(5)
end
def new
@story = Story.new
end
# GET /stories/1/edit
def edit
chapter_numbers = params[:chapter_numbers].to_i
@story = Story.includes(:chapters, :items).find(params[:id])
generate_chapters(chapter_numbers)
@chapter_count = @story.chapters.count
@chapters = @story.chapters.page(params[:page]).per(10)
@all_chapters = @story.chapters
@page = params[:page]
params[:change_page] == 'true' ? @last_chapter = nil : @last_chapter = params[:last_chapter]
end
def edit_story
@story = Story.find(params[:story_id])
end
def edit_items
@story = Story.find(params[:story_id])
if @story.items.empty?
item = @story.items.build
end
end
def favorite
type = params[:type]
story = Story.find(params[:id])
if type == "favorite"
current_user.favorites << story
redirect_to :back, notice: "Você favoritou #{story.title}"
elsif type == "unfavorite"
current_user.favorites.delete(story)
redirect_to :back, notice: "Você deixou de favoritar #{story.title}"
else
redirect_to :back, notice: 'Nada aconteceu.'
end
end
def update_chapter_number
@story = Story.find(params[:story_id])
quantity = params[:quantity].to_i
params[:type] == 'sum' ? add_chapters(@story, quantity) : remove_chapters(@story, quantity)
end
def graph
@story = Story.find(params[:story_id])
end
def graph_json
chapters = Chapter.includes(:decisions).by_story(params[:id])
@chapters = Story.graph(chapters)
respond_to do |format|
format.json { render json: @chapters.to_json }
end
end
def graph_json_show
chapters_of_story = Chapter.by_story(params[:id])
chapters = chapters_of_story.includes(:decisions)
@chapters = Story.graph(chapters)
respond_to do |format|
format.json { render json: @chapters.to_json }
end
end
def node_update
chapter = Chapter.by_story(params[:id]).where(reference: params[:cap].gsub("Cap ","")).first
chapter.x = params[:x].to_f
chapter.y = params[:y].to_f
respond_to do |format|
if chapter.save
format.html { render nothing: true, notice: 'Update SUCCESSFUL!', status: 200 }
else
format.json { render nothing: true, status: 500 }
end
end
end
def use_item
adventurer = current_user.adventurers.by_story(params[:story_id]).first
result = adventurer.use_item(params["item-id"], params[:attribute], params[:modifier])
if result.present?
result[:message] = I18n.t('actions.messages.adventurer_update_success')
else
result[:message] = I18n.t('actions.messages.adventurer_update_fail')
end
respond_to do |format|
format.json { render json: result.to_json }
end
end
def buy_item
adventurer = current_user.adventurers.where(story_id: params[:story_id]).first
modifier_shop = ModifierShop.find(params[:shop_id])
item = modifier_shop.item
adventurer_modifier_shop = adventurer.adventurers_shops.where(modifier_shop_id: params[:shop_id]).first
if adventurer.adventurer_modifier_shop_present? params[:shop_id]
update_same_adventurer_shop(adventurer, adventurer_modifier_shop, modifier_shop, item)
else
create_new_adventurer_shop(adventurer, adventurer_modifier_shop, modifier_shop, item, params[:shop_id])
end
end
def select_weapon
adventurer = Adventurer.find params[:adventurer_id]
if adventurer.select_weapon(params[:item_id])
redirect_to :back, notice: I18n.t('actions.success_weapon_select')
else
redirect_to :back, alert: I18n.t('actions.fail_weapon_select')
end
end
def erase_image
current_chapter = Chapter.find(params[:chapter_id])
current_chapter.image_file_name = nil
current_chapter.image_content_type = nil
current_chapter.image_file_size = 0
current_chapter.save
render nothing: true
end
def publish
story = Story.find(params[:story_id])
publish_story(story)
end
# POST /stories
# POST /stories.json
def create
@story = Story.new(story_params)
respond_to do |format|
if @story.save
format.html { redirect_to edit_story_path(id: @story, chapter_numbers: params[:story][:chapter_numbers]), notice: I18n.t('actions.messages.create_success') }
format.json { render json: @story, status: :created, location: @story }
else
@errors = get_errors(@story)
format.html { redirect_to new_story_path, alert: {errors: @errors} }
format.json { render json: @story.errors, status: :unprocessable_entity }
end
end
end
def update_tabs
@story = Story.find(params[:story_id].to_i)
respond_to do |format|
if @story.update_attributes(params[:story])
format.html { render nothing: true}
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @story.errors, status: :unprocessable_entity }
end
end
end
# PUT /stories/1
# PUT /stories/1.json
def update
@story = Story.find(params[:id])
if @story.update_attributes(story_params)
redirect_story(@story, params)
else
@chapters = @story.chapters
@errors = get_errors(@story)
flash[:alert] = {errors: @errors}
respond_to do |format|
case params[:commit]
when t('actions.edit_items')
@errors = get_errors(@story)
format.html { render action: :edit_items, controller: :stories, alert: @errors }
format.json { render json: {errors: @errors.to_json,
chapters_with_errors: @chapters_with_errors},
status: :unprocessable_entity }
when t('actions.save_story')
@chapters_with_errors = get_chapters_with_errors(@story)
format.html { render action: :edit_story, controller: :stories, alert: @errors }
format.json { render json: {errors: @errors.to_json,
chapters_with_errors: @chapters_with_errors},
status: :unprocessable_entity }
end
end
end
end
def auto_save
@story = Story.find(params[:story_id].to_i)
respond_to do |format|
if @story.update_attributes(params[:story])
format.html { render nothing: true}
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @story.errors, status: :unprocessable_entity }
end
end
end
# DELETE /stories/1
# DELETE /stories/1.json
def destroy
@story = Story.find(params[:id])
@story.destroy
respond_to do |format|
format.html { redirect_to profile_path(current_user) }
format.json { head :no_content }
end
end
private
def publish_story(story)
if story.published
story.published = false
else
story.published = true
end
if story.save
data = format_publish_message(story, success: true)
else
data = format_publish_message(story, success: true)
end
respond_to do |format|
format.json { render json: data.to_json }
end
end
def redirect_story(story, params)
case params[:commit]
when I18n.t('actions.save')
redirect_to :back, notice: I18n.t('actions.messages.save_success')
when I18n.t('actions.edit_items')
redirect_to story_edit_items_path(story), notice: I18n.t('actions.messages.data_saved')
when I18n.t('actions.save_story')
redirect_to story_edit_story_path(story), notice: I18n.t('actions.messages.data_saved')
else
redirect_to story, notice: I18n.t('actions.messages.update_success')
end
end
def add_chapters(story,num_chapters)
message = add_chapters_by_quantity(story, num_chapters)
redirect_to edit_story_path(story), notice: message
end
def remove_chapters(story, num_chapters)
message = remove_chapters_by_quantity(story, num_chapters)
redirect_to edit_story_path(story), notice: message
end
def update_same_adventurer_shop(adventurer, adventurer_shop, modifier_shop, item)
unless adventurer.cant_buy?(adventurer_shop, modifier_shop.price)
adventurer_shop.quantity -= 1
if adventurer_shop.save
adventurer.buy_item(item, modifier_shop)
redirect_to :back, notice: I18n.t('actions.messages.buy_success')
else
redirect_to :back, alert: I18n.t('actions.messages.problem_fail')
end
else
redirect_to :back, alert: I18n.t('actions.messages.buy_fail')
end
end
def create_new_adventurer_shop(adventurer, adventurer_shop, modifier_shop, item, shop_id)
unless adventurer.cant_buy?(adventurer_shop, modifier_shop.price)
adventurer.adventurers_shops.create(modifier_shop_id: shop_id, quantity: modifier_shop.quantity - 1)
adventurer.buy_new_item(item, modifier_shop.price)
redirect_to :back, notice: I18n.t('actions.messages.buy_success')
else
redirect_to :back, alert: I18n.t('actions.messages.buy_fail')
end
end
def set_story
@story = Story.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def story_params
params.require(:story).permit(:resume,
:title,
:prelude,
:initial_gold,
:user_id,
:chapter_numbers,
:cover,
:published,
:chapter_numbers,
items_attributes: [:id, :description, :name, :story_id, :usable, :type, :damage, :attr, :modifier, :_destroy],
chapters_attributes: [:id,
:content,
:reference,
:story_id,
:image,
:x,
:y,
:color,
:_destroy,
decisions_attributes: [:id, :destiny_num, :chapter_id, :item_validator, :_destroy],
monsters_attributes: [:id, :skill, :energy, :name, :chapter_id, :_destroy],
modifiers_attributes_attributes: [:id, :attr, :chapter_id, :quantity, :_destroy],
modifiers_items_attributes: [:id, :chapter_id, :item_id, :quantity, :_destroy, items_attributes: [:id, :description, :name, :story_id, :_destroy]],
modifiers_shops_attributes: [:id, :chapter_id, :item_id, :price, :quantity, :_destroy, items_attributes: [:id, :description, :name, :story_id, :_destroy]],
items_attributes: [:id, :description, :name, :type, :damage, :story_id, :_destroy]
]) if params[:story]
end
end
|
class User < ActiveRecord::Base
has_many :shouts
include Clearance::User
end
|
#
# Copyright 2009 Huygens Instituut for the History of the Netherlands, Den Haag, The Netherlands.
#
# This file is part of New Women Writers.
#
# New Women Writers is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# New Women Writers is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with New Women Writers. If not, see <http://www.gnu.org/licenses/>.
#
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def admin?
logged_in? && @current_user.level == 1
end
def delete_button(subject, subjectname)
link_to image_tag("delete.png", :border=>0),{:action => 'destroy', :id => subject.id}, :title => "delete this "+ subjectname,
:confirm => "This will delete this "+ subjectname +".\n WARNING: All data belonging to this "+subjectname+" will be permanently deleted! \nAre you sure?",
:method => :delete
end
def edit_button(subject, subjectname)
link_to image_tag("edit.png", :border=>0),{:action => "edit", :id => subject.id}, :title => "edit this "+ subjectname
end
def editor?
logged_in? && @current_user.level == 2 or logged_in? && @current_user.level == 1
end
def flash_notice
if flash[:notice]
content_tag('div', h(flash[:notice]), {:id => "flash_notice", :class=>"message"})
end
end
def logged_in?
@current_user.is_a?(User)
end
def no_records(things)
content_tag('div', "No records found", {:id => "no_records", :class=>"message"}) if things.empty?
end
def sort_link_helper(list,text, field)
field += " DESC" if params[:sort] == field
link_to_function text, "document.getElementById('sort').value='"+field+"'; document.formnaam.submit()"
end
def sort_td_class_helper(field)
result = 'class="sortup"' if params[:sort] == field
result = 'class="sortdown"' if params[:sort] == field + " DESC"
result = 'class="columnheader"'
return result
end
def navigation (subject, searchby_text)
result=hidden_field_tag('per_page', params[:per_page]) + "\n"
result+=hidden_field_tag('sort', params[:sort])+ "\n"
result+=hidden_field_tag('page', params[:page])+ "\n"
result+="<div>\n"
result+="<legend>Search by #{searchby_text}</legend>\n"
result+= text_field_tag(:search_name, params[:search_name], :onblur=>'document.formnaam.submit()' )+ "\n"
result+= image_submit_tag("search.png", :title=>"search")+ "\n"
result+= link_to image_tag("reload.png", :title=>"show all")
result+="</div>\n"
result+="<div class=\"recsfound\">\n"
result+="Found #{@count} records, \n"
result+= text_field_tag(:per_page, params[:per_page], :size => 2, :onblur=>'document.formnaam.submit()' )+ "\n"
result+="per page\n"
result+="</div>\n"
return result
end
def sorting_lists
result="<form name='formnaam'>"
result+=hidden_field_tag('sort', params[:sort])+ "\n"
result+="</form>"
return result
end
=begin
observe_field(:search_name,
:frequency => 0.50,
:before => "Element.show('spinner')",
:success => "Element.hide('spinner')",
:update =>:authors_list,
:url => { :action => :index },
:with => "'search_name=' +value")
image_tag("ajax-loader.gif",
:align => "absmiddle",
:border => 0,
:id => "spinner",
:style =>"display: none;" )
=end
def one_to_many_helper(this_collection, name_collection, attribute, backtodestination)
output="<table>"
this_collection.each do |one|
output+="<tr id=\""+name_collection+"_"+one.id.to_s+"\">"
output+="<td>"
output+=link_to_function image_tag("xxcancel.png", :border=>0), "deleteOneFromMany('#{name_collection}', #{one.id.to_s})"
output+="</td>"
output+="<td>"
output+=one.send(attribute)
output+="</td>"
output+="</tr>"
end
output+="</table>"
output+='<div><input type="text" name="'+name_collection+'[]['+attribute+']" /></div>'
output+= link_to_function image_tag("xxadd.png", :border=>0)+"add this #{name_collection.singularize}" , "addOneToMany('"+backtodestination+"')"
return output
end
# Used to make inputfields for author url, work url or reception url
def one_to_many_link_helper(this_collection, name_collection, attribute1, attribute2, backtodestination)
output="<table>"
this_collection.each do |one|
output+="<tr id=\""+name_collection+"_"+one.id.to_s+"\">"
output+="<td>"
output+=link_to_function image_tag("xxcancel.png", :border=>0), "deleteOneFromMany('#{name_collection}', #{one.id.to_s})"
output+="</td>"
output+="<td>"
output+=one.send(attribute1)+" - "+one.send(attribute2)
output+="</td>"
output+="</tr>"
end
output+="</table>"
output+='<div>Title: <input type="text" name="'+name_collection+'[]['+attribute1+']" />'
output+=' Url: <input type="text" name="'+name_collection+'[]['+attribute2+']" /></div>'
output+= link_to_function image_tag("xxadd.png", :border=>0)+"add this weblink" , "addOneToMany('"+backtodestination+"')"
return output
end
def approved?(object_name, object_id)
@unapproved = Change.find(:all, :conditions => { :approved => 0, :object_name => object_name, :object_id => object_id})
@unapproved.blank?
end
def cut_at(string, maxlength)
if(string.length>maxlength) then
string=string[0..maxlength-3]+"..."
end
return string
end
=begin
def sort_link_helper_old(list,text, field)
key = field
key += " DESC" if params[:sort] == field
options = {
:url => {:action => 'index', :params => params.merge({:sort => key, :page => nil})},
:update => list,
:before => "Element.hide('spinner')",
:success => "Element.hide('spinner')"
}
html_options = {
:title => "Sort by this field",
:href => url_for(:action => 'index', :params => params.merge({:sort => key, :page => nil}))
}
link_to_remote(text, options, html_options)
end
=end
end
|
module Deployinator
module Stacks
module Twbt
def uat_version
%x{ssh deploy@pitch160.anchor.net.au cat /home/deploy/apps/uat_12wbt/current/REVISION | cut -c1-7}
end
def prod_version
%x{ssh deploy@martingale.anchor.net.au cat /home/deploy/apps/12wbt/current/REVISION | cut -c1-7}
end
def current_uat_build
uat_version
end
def current_prod_build
prod_version
end
def next_build
%x{git ls-remote git@github.com:red-ant/12wbt HEAD | cut -c1-7}.chomp
end
def prod_deploy(options={})
run_cmd %Q(cap deploy -S stage=production)
end
def uat_deploy(options={})
run_cmd %Q(cap deploy -S stage=uat)
# run_cmd %Q{source ~/.rvm/scripts/rvm; cd /home/jago/work/12wbt;rvm use @deploy;cap deploy -S stage=uat}
end
def twbt_environments
[
{
:name => "uat",
:method => "uat_deploy",
:current_version => uat_version,
:current_build => current_uat_build,
:next_build => next_build
},
{
:name => "production",
:method => "prod_deploy",
:current_version => prod_version,
:current_build => current_prod_build,
:next_build => next_build
}
]
end
def twbt_production_version
# %x{curl http://my-app.com/version.txt}
"cf44aab-20110729-230910-UTC"
end
def twbt_head_build
# the build version you're about to push
# %x{git ls-remote #{your_git_repo_url} HEAD | cut -c1-7}.chomp
"11666e3"
end
def twbt_production(options={})
log_and_stream "Fill in the twbt_production method in stacks/twbt.rb!<br>"
# log the deploy
log_and_shout :old_build => environments[0][:current_build].call, :build => environments[0][:next_build].call
end
end
end
end
|
class Pwb::Devise::RegistrationsController < Devise::RegistrationsController
def edit_success
return render "/devise/registrations/edit_success"
end
# The default url to be used after updating a resource. You need to overwrite
# this method in your own RegistrationsController.
def after_update_path_for(resource)
# signed_in_root_path(resource)
pwb.user_edit_success_path
end
end
|
class ProductoTrabajo < ActiveRecord::Base
attr_accessible :detalle
validates :detalle, :presence => true
end
|
class Subreddit < ApplicationRecord
def self.update_list(subreddit_array)
return if subreddit_array.blank?
Subreddit.delete_all
subreddit_array.each do |com|
next if com.to_s.strip.blank?
s = Subreddit.new
s.subreddit_name = com
s.save!
end
end
end
|
# Permission class model
class Permission < ActiveRecord::Base
has_many :user_permissions
has_many :users, through: :user_permissions, dependent: :destroy
has_many :role_permissions
has_many :roles, through: :role_permissions, dependent: :destroy
name_message = 'permission must have a unique name'
name_length_message = 'permission name must be 2-20 alphabetic characters'
validates :name,
uniqueness: { message: name_message },
:presence => { message: name_message },
:length => { minimum: 2, message: name_length_message },
:format => { with: /[A-za-z]{2,20}/, message: name_length_message }
end
|
module UsersHelper
include Rack::Recaptcha::Helpers
# TODO cache these
def user_avatar(user, size="150x150#")
return "" if user.avatar.blank?
image_tag(user.avatar.thumb(size).url,
class: 'avatar',
alt: user.username
).html_safe
end
def user_avatar_small(user)
user_avatar(user, '75x75#')
end
def user_username(user)
return user.username unless user.verified?
"#{user.username} <i class='icon verified tip' title='#{user.verified_type_s}' data-tip-class='verified'></i>".html_safe
end
def user_profile_status(user)
if !user.verified?
if user.custom_avatar.present? && !user.user_audiences.any?
return "45"
elsif !user.custom_avatar.present? && user.user_audiences.any?
return "60"
elsif user.custom_avatar.present? && user.user_audiences.any?
return "80"
else
return "25"
end
elsif user.verified?
if user.custom_avatar.present? && !user.user_audiences.any?
return "70"
elsif !user.custom_avatar.present? && user.user_audiences.any?
return "60"
elsif user.custom_avatar.present? && user.user_audiences.any?
return "100"
else
return "40"
end
end
end
end
|
class Identity < ActiveRecord::Base
#t.string :name
#t.string :password_digest
validates :name, presence: true, uniqueness:true
validates :password, length: {minimum: 6}
has_secure_password
has_one :user
end
|
class AddSocialLinksToCoaches < ActiveRecord::Migration[5.0]
def change
add_column :coaches, :website, :string
add_column :coaches, :facebook, :string
add_column :coaches, :instagram, :string
add_column :coaches, :youtube, :string
add_column :coaches, :twitter, :string
add_column :coaches, :linkedin, :string
add_column :coaches, :pinterest, :string
end
end
|
module Spree
module Concerns
module Indexable
class ResultList
include Enumerable
attr_accessor :results
attr_accessor :total
attr_accessor :from
def initialize(results, from, total)
self.results = results
self.from = from
self.total = total
end
def each(*args, &block)
results.each(*args, &block)
end
end
extend ActiveSupport::Concern
included do
attr_accessor :version
after_save :update_index
after_destroy :update_index
end
module ClassMethods
def client
@client ||= Elasticsearch::Client.new log: true, hosts: configuration.hosts
end
def configuration
ElasticsearchSettings
end
def delete_all
begin
client.perform_request 'DELETE', configuration.index
rescue => e
# Throws exception if the index doesn't exist
end
end
# Get a document in Elasticsearch based on id
def get(id)
result = client.get id: id,
type: type,
index: configuration.index
object_attributes = result["_source"]
object_attributes.except!(*exclude_from_response)
model = self.new(object_attributes)
model.version = result["_version"]
model
end
# Used during initialization of the application to create or update the mapping.
# The actual implementation of the mapping is defined in the models.
def mapping
{
type.to_sym => {
properties: self.type_mapping
}
}
end
# The actual searching in Elasticsearch.
def search(args = {})
search_args = {}
search_args[:body] = self::ElasticsearchQuery.new(args).to_hash
search_args[:index] = configuration.index
search_args[:type] = type
result = client.search search_args
result_list = result["hits"]["hits"].map do |item|
object_attributes = item["_source"]
object_attributes.except!(*exclude_from_response)
model = new(object_attributes)
model.version = item["_version"]
model
end
ResultList.new(result_list, Integer(args.fetch(:from, 0)), result["hits"]["total"])
end
def type
name.underscore.gsub('/','_')
end
end
def client
self.class.client
end
def configuration
self.class.configuration
end
def remove_from_index
client.delete id: id,
type: type,
index: configuration.index
end
def index
doc = to_hash
doc.delete(:id)
doc.delete(:version)
result = client.index id: self.id,
type: type,
index: configuration.index,
body: doc
unless result['ok']
raise "Indexing Error: #{result.inspect}"
end
result
end
def type
self.class.type
end
def update_index
self.index
end
end
end
end
|
class ThemesController < ApplicationController
def random
category = Category.find(params[:category_id])
@theme = category.themes.all.sample
end
end |
require 'main/resources/v1/recipe_pb'
require 'google/protobuf/well_known_types'
class Recipe < ApplicationRecord
belongs_to :user
has_many :ingredients, -> { order(:position) }, dependent: :destroy
has_many :steps, -> { order(:position) }, dependent: :destroy
validates :title, presence: true
validates :description, presence: true
def as_protocol_buffer(request_context: nil)
Main::Resources::V1::Recipe.new(
id: id,
title: title,
user: user&.as_protocol_buffer,
ingredients: ingredients&.map(&:as_protocol_buffer),
steps: steps&.map(&:as_protocol_buffer),
description: description,
created_at: Google::Protobuf::Timestamp.new.tap {|t| t.from_time(created_at) },
updated_at: Google::Protobuf::Timestamp.new.tap {|t| t.from_time(updated_at) },
)
end
end
|
# ==========================================================================
# Project: Lebowski Framework - The SproutCore Test Automation Framework
# License: Licensed under MIT license (see License.txt)
# ==========================================================================
module Lebowski
module Foundation
#
# ProxyObject is the root object for all objects that are to proxy an object within a
# web brower. This provides all of the core functionality allowing you to communicate with
# a remote object and access other remote objects through the use of relative property paths.
#
# In the case where you have created a custom SproutCore object and want to have a proxy for it
# then your proxy must inherit from the SCObject class that inherits this class.
#
class ProxyObject
include Lebowski::Foundation
include Lebowski::Foundation::Mixins::WaitActions
include Lebowski::Foundation::Mixins::DefinePathsSupport
attr_reader :parent, # The parent object of this object. Must derive from Lebowski::Foundation::ProxyObject
:rel_path, # The relative path to the remote object using SC property path notation
:driver # The SproutCore driver that is used to actually communicate with the remote object
attr_accessor :name # A name for this object. Useful for printing out statements and debugging
#
# Creates a new proxy object instance.
#
# Try to refrain from overriding this method. Instead, if you wish to perform some operations
# during the time an object is being initialized, override the init_ext method
#
# @param parent {Object} parent object of this object. Must inherit from Lebowski::Foundation::ProxyObject
# @param rel_path {String} a relative path to the remote object (e.g. 'foo', 'foo.bar')
# @param driver {Object} used to remotely communicate with the remote object.
#
# @see #init_ext
#
def initialize(parent=nil, rel_path=nil, driver=nil)
if not init_expected_parent_type.nil?
if not parent.kind_of? init_expected_parent_type
raise ArgumentInvalidTypeError.new "parent", parent, init_expected_parent_type
end
end
@parent = parent
@rel_path = rel_path
@driver = driver
@guid = nil
@cached_proxy_objects = {}
@defined_proxies = {}
@name = ""
init_ext()
end
#
# Override this method for any initialization procedures during the time the object is being
# inialized
#
# @see #initialize
#
def init_ext()
end
#
# Use when you wish to represent a proxied object as something else other then the proxy
# returned by this object when accessed with a relative path using []. This is useful
# in cases where you have a view that is simply composed of other views but itself is not
# custom view inherited from SC.View. As an example, it is common in SproutCore to
# create a complex view that lives only within an SC.Page, like so:
#
# MyApp.mainPage = SC.Page.create({
#
# composedView: SC.View.design({
# layout: { top: 0, bottom: 0, left: 0, right: 0 },
# childViews: 'buttonOne buttonTwo statusLabel'.w(),
#
# buttonOne: SC.ButtonView.design({
# ...
# }),
#
# buttonTwo: SC.ButtonView.design({
# ...
# }),
#
# statusLabel: SC.LabelView.design({
# ...
# })
# })
#
# })
#
# Since the root view (composedView) is just a basic SC.View, accessing it using
# the proxy's [] convention would just give you back a basic View proxy. This then
# means you have to access the child views explicitly every time you want to interact
# with the composed view. This can be brittle since the view's structure can change.
# Instead you can make a proxy to abstract away the interal structure and make it
# easier to work with the view. Therefore, we could make a proxy as follows:
#
# ComposedView < Lebowski::Foundation::Views::View
#
# def click_button_one()
# self['buttonOne'].click
# end
#
# def click_button_two()
# self['buttonTwo'].click
# end
#
# def status()
# return self['statusLabel.value']
# end
#
# end
#
# With the proxy above, you can then do the following:
#
# view = App['mainPage.composedView', View]
# view = view.represent_as(ComposedView)
# view.click_button_one
# status = view.status
#
def represent_as(type)
if not (type.kind_of?(Class) and type.ancestors.member?(ProxyObject))
raise ArgumentInvalidTypeError.new "type", type, 'class < ProxyObject'
end
obj = type.new @parent, @rel_path, @driver
return obj
end
#
# Returns the absolute path of this object based on the parent object heirarchy. As
# an example, this object's parent has an absolute path of 'foo' and this object has
# relative path of 'bar', then the absolute path will be 'foo.bar'
#
def abs_path()
if not @abs_path.nil?
return @abs_path
end
if @parent.nil? or @parent.abs_path.nil?
return @rel_path
end
@abs_path = "#{@parent.abs_path}.#{rel_path}"
return @abs_path
end
#
# Returns the absolute path given a relative path. Say, for example, that a
# proxy object has an absolute path of 'mainPage.mainPane.someView'. When
# given a relative path of 'foo.bar', the returned value would be:
#
# 'mainPage.mainPane.someView.foo.bar'
#
def abs_path_with(rel_path)
path = abs_path
return rel_path if path.nil?
return "#{path}.#{rel_path}"
end
#
# Gets the remote SproutCore GUID for this object
#
def sc_guid()
# We only need to fetch the remote GUID once since it never changes for a given instance
@guid = @driver.get_sc_guid(abs_path) if @guid.nil?
return @guid
end
#
# Gets the remote SC class name for this object
#
def sc_class()
# We only need to fetch the remote SC class name once since it never changes for a given instance
@class_name = @driver.get_sc_object_class_name(abs_path) if @class_name.nil?
return @class_name
end
#
# Gets all the remote SproutCore classes that the proxied object derives from. This will return
# an array of strings representing the names of the classes. As an example, if the
# proxy was communicating with an object that was of type SC.ButtonView then the
# result would be the following:
#
# ['SC.ButtonView', 'SC.View', 'SC.Object']
#
# The last item in the array is always 'SC.Object' since that is the root object for all
# SproutCore objects.
#
def sc_all_classes()
@all_class_names = @driver.get_sc_object_class_names(abs_path) if @all_class_names.nil?
return @all_class_names
end
#
# Checks if the remote proxied object is a kind of given SC class
#
def sc_kind_of?(type)
if not (type.kind_of?(Class) or type.kind_of?(String))
raise ArgumentInvalidTypeError.new "type", type, 'class < SCObject', String
end
if type.kind_of?(Class) and type.ancestors.member?(SCObject)
type = type.represented_sc_class
end
type = type.downcase
result = sc_all_classes.detect do |val|
val.downcase == type
end
return (not result.nil?)
end
def sc_type_of(rel_path)
return @driver.get_sc_type_of(abs_path_with(rel_path))
end
def sc_path_defined?(rel_path)
return (not sc_type_of(rel_path) == SC_T_UNDEFINED)
end
def none?(rel_path)
type = sc_type_of(rel_path)
return (type == SC_T_UNDEFINED or type == SC_T_NULL)
end
def object?(rel_path)
type = sc_type_of(rel_path)
return (type == SC_T_OBJECT or type == SC_T_HASH)
end
# DEPRECATED
def proxy(klass, rel_path)
puts "DEPRECATED: proxy is deprecated. use define_proxy instead"
puts "... klass = #{klass}"
puts "... rel_path = #{rel_path}"
define_proxy(klass, rel_path)
end
# DEPRECATED
def define(path, rel_path=nil, expected_type=nil)
puts "DEPRECATED: define is deprecated. use define_path instead"
puts "... path = #{path}"
puts "... rel_path = #{rel_path}"
puts "... expected_type = #{expected_type}"
define_path(path, rel_path, expected_type)
end
#
# Defines a path proxy for a relative path on this proxy object. The path proxy
# will be loaded only when actually requested for use.
#
# @param klass The klass to use as the path proxy
# @param rel_path The relative path agaist this proxy object
#
def define_proxy(klass, rel_path)
if (not rel_path.kind_of?(String)) or rel_path.empty?
raise ArgumentError.new "rel_path must be a valid string"
end
if not (klass.kind_of?(Class) and klass.ancestors.member?(ProxyObject))
raise ArgumentInvalidTypeError.new "klass", klass, 'class < ProxyObject'
end
@defined_proxies[rel_path] = klass
end
#
# Given a relative path, unravel it to access an object. Unraveling means to take
# any defined path in the given relative path and convert the entire path back
# into a full relative path without definitions.
#
def unravel_relative_path(rel_path)
path_parts = rel_path.split '.'
full_rel_path = ""
defined_path = nil
counter = path_parts.length
for path_part in path_parts do
path = defined_path.nil? ? path_part : "#{defined_path}.#{path_part}"
if path_defined? path
defined_path = path
else
break
end
counter = counter - 1
end
full_rel_path << self.defined_path(defined_path).full_rel_path if (not defined_path.nil?)
if (counter > 0)
full_rel_path << "." if (not defined_path.nil?)
full_rel_path << path_parts.last(counter).join('.')
end
return full_rel_path
end
#
# The primary method used to access a proxied object's properties. Accessing
# a property is done using a relative property path. The path is a chain of
# properties connected using dots '.'. The type is automatically determined, but
# in cases where a particular type is expected, you can optionally supply what the
# expected type should be.
#
# As an example, to access an object's property called 'foo', you can do the
# following:
#
# value = object['foo']
#
# If you expect the value's type to be, say, an number, you can do the following:
#
# value = object['foo', :number]
#
# In the case where you expect the value to be a type of object you can do one
# of the following:
#
# value = object['foo', 'SC.SomeObject']
#
# value = object['foo', SomeObject]
#
# In the first case, you are supply the object type as a string, in the second case
# you are supplying the expected type with a proxy class. For the second option to
# work you must first supply the proxy to the proxy factory.
#
# To access a property through a chain of objects, you supply a relative path, like
# so:
#
# value = object['path.to.some.property']
#
# Remember that the path is relative to the object you passed the path to. The approach
# is used to work with how you would normally access properties using the SproutCore
# framework.
#
# The fundamental types detected within the web browser are the following:
#
# Null - null in JavaScript
# Error - SproutCore error object
# String - string in JavaScript
# Number - number in JavaScript
# Boolean - boolean in JavaScript
# Hash - a JavaScript hash object
# Object - a SproutCore object
# Array - a JavaScript array
# Class - A SproutCore class
#
# Based on the value's type within the browser, this method will translate the value as
# follows:
#
# Null -> nil
# Error -> :error
# String -> standard string
# Number -> standard number
# Boolean -> standard boolean
# Hash -> a generic proxy object
# Object -> closest matching proxy object
# Array -> standard array for basic types; an object array (ObjectArray) for objects
# Class -> a generic proxy object
#
# If the given relative path tries to reference a property that is not defined then :undefined
# is returned.
#
# The two special cases are when the basic type of the relative path is a SproutCore object or
# an array. In the case of a SproutCore object, the closest matching object type will be returned
# based on what proxies have been provided to the proxy factory. For instance, let's say you have
# custom view that derives from SC.View. If no proxy has been made for the custom view then
# the next closest proxy will be returned, which would be a View proxy that is already part
# of the lebowski framework. If your require a proxy to interact with the custom view then you
# need to add that proxy to the proxy framework.
#
# When the type is an array, the proxy object will check the content of the array to determine
# their type. If all the content in the array are of the same type then it will return a
# corresponding array made up content with that type. So, for example, if an object has
# a property that is an array of strings then a basic array of string will be returned. In the
# case where the array contains either hash objects or SproutCore objects then an ObjectArray
# will be returned.
#
def [](rel_path, expected_type=nil)
if (not rel_path.kind_of?(String)) or rel_path.empty?
raise ArgumentError.new "rel_path must be a valid string"
end
if @cached_proxy_objects.has_key? rel_path
return @cached_proxy_objects[rel_path]
end
defined_proxy = @defined_proxies.has_key?(rel_path) ? @defined_proxies[rel_path] : nil
path_defined = path_defined? rel_path
if path_defined
path = defined_path rel_path
expected_type = path.expected_type if (path.has_expected_type? and expected_type.nil?)
end
unraveled_rel_path = unravel_relative_path rel_path
value = fetch_rel_path_value unraveled_rel_path, expected_type
if value.kind_of? ProxyObject
value = value.represent_as(defined_proxy) if (not defined_proxy.nil?)
@cached_proxy_objects[rel_path] = value if (path_defined or not defined_proxy.nil?)
end
return value
end
#
# Retain a reference to the original eql? method so we can still use it
#
alias_method :__eql?, :eql?
#
# Override the == operator so that a proxy object can be compared to another
# proxy object via their SproutCore GUIDs
#
def ==(obj)
return (self.sc_guid == obj.sc_guid) if obj.kind_of?(ProxyObject)
return super(obj)
end
alias_method :eql?, :==
#
# Override method_missing so that we can access a proxied object's properties using
# a more conventional Ruby approach. So instead of accessing an object's property
# using the [] convention, we can instead do the following:
#
# value = proxied_object.foo # compared to proxied_object['foo']
#
# This will also translate the name of property into camel case that is normally
# used in JavaScript. So, if an object in JavaScript has a property with the
# name 'fooBar', you can access that property using the standard Ruby convention
# like so:
#
# value = proxied_object.foo_bar
#
# It will be converted back into 'fooBar'. If the property does not exist
# on the proxied object then an exception will be thrown. If you want to access
# property without an exception being thrown then use the [] convention using
# a relative property path string.
#
def method_missing(sym, *args, &block)
if (not sym.to_s =~ /\?$/) and (args.length == 0)
camel_case = Util.to_camel_case(sym.to_s)
return self[camel_case] if sc_path_defined?(camel_case)
end
super
end
private
def init_expected_parent_type()
return nil
end
def rel_path_first_part(rel_path)
first_path_part = rel_path.match(/^((\w|-)*)\./)
first_path_part = rel_path if first_path_part.nil?
first_path_part = first_path_part[1] if first_path_part.kind_of?(MatchData)
return first_path_part
end
def rel_path_sub_path(rel_path, first_path_part)
sub_path = (first_path_part != rel_path) ? rel_path.sub(/^(\w|-)*\./, "") : ""
return sub_path
end
def fetch_rel_path_value(rel_path, expected_type)
type = sc_type_of(rel_path)
case type
when SC_T_NULL
return handle_type_null(rel_path, expected_type)
when SC_T_UNDEFINED
return handle_type_undefined(rel_path, expected_type)
when SC_T_ERROR
return handle_type_error(rel_path, expected_type)
when SC_T_STRING
return handle_type_string(rel_path, expected_type)
when SC_T_NUMBER
return handle_type_number(rel_path, expected_type)
when SC_T_BOOL
return handle_type_bool(rel_path, expected_type)
when SC_T_ARRAY
return handle_type_array(rel_path, expected_type)
when SC_T_HASH
return handle_type_hash(rel_path, expected_type)
when SC_T_OBJECT
return handle_type_object(rel_path, expected_type)
when SC_T_CLASS
return handle_type_class(rel_path, expected_type)
else
raise StandardError.new "Unrecognized returned type '#{type}' for path #{abs_path_with(rel_path)}"
end
end
def handle_type_null(rel_path, expected_type)
if (not expected_type.nil?) and not (expected_type == :null)
raise UnexpectedTypeError.new(abs_path_with(rel_path), expected_type, SC_T_NULL, :null)
end
return nil
end
def handle_type_undefined(rel_path, expected_type)
if (not expected_type.nil?) and not (expected_type == :undefined)
raise UnexpectedTypeError.new(abs_path_with(rel_path), expected_type, SC_T_UNDEFINED, :undefined)
end
return :undefined
end
def handle_type_error(rel_path, expected_type)
if (not expected_type.nil?) and not (expected_type == :error)
raise UnexpectedTypeError.new(abs_path_with(rel_path), expected_type, SC_T_ERROR, :error)
end
return :error
end
def handle_type_bool(rel_path, expected_type)
value = @driver.get_sc_path_boolean_value(abs_path_with(rel_path))
if (not expected_type.nil?) and not (expected_type == :boolean or expected_type == :bool)
raise UnexpectedTypeError.new(abs_path_with(rel_path), expected_type, SC_T_BOOL, value)
end
return value
end
def handle_type_string(rel_path, expected_type)
value = @driver.get_sc_path_string_value(abs_path_with(rel_path))
if (not expected_type.nil?) and not (expected_type == :string)
raise UnexpectedTypeError.new(abs_path_with(rel_path), expected_type, SC_T_STRING, value)
end
return value
end
def handle_type_number(rel_path, expected_type)
value = @driver.get_sc_path_number_value(abs_path_with(rel_path))
if (not expected_type.nil?) and not (expected_type == :number)
raise UnexpectedTypeError.new(abs_path_with(rel_path), expected_type, SC_T_NUMBER, value)
end
return value
end
def handle_type_class(rel_path, expected_type)
# TODO: Need to handle this case better
value = ProxyObject.new self, rel_path, @driver
if (not expected_type.nil?) and not (expected_type == :class)
raise UnexpectedTypeError.new(abs_path_with(rel_path), expected_type, SC_T_CLASS, value)
end
return value
end
def handle_type_hash(rel_path, expected_type)
value = ProxyObject.new self, rel_path, @driver
if (not expected_type.nil?) and not (expected_type == :object or expected_type == :hash)
raise UnexpectedTypeError.new(abs_path_with(rel_path), expected_type, SC_T_HASH, value)
end
return value
end
def handle_type_object(rel_path, expected_type)
value = nil
class_names = @driver.get_sc_object_class_names(abs_path_with(rel_path))
matching_class = class_names.detect { |name| ProxyFactory.has_key?(name) }
if matching_class.nil?
value = ProxyFactory.create_proxy(Lebowski::Foundation::SCObject, self, rel_path)
else
value = ProxyFactory.create_proxy(matching_class, self, rel_path)
end
if not expected_type.nil?
got_expected_type = (expected_type == :object or value.sc_kind_of?(expected_type))
if not got_expected_type
raise UnexpectedTypeError.new(abs_path_with(rel_path), expected_type, SC_T_OBJECT, value)
end
end
return value
end
def handle_type_array(rel_path, expected_type)
content_type = @driver.get_sc_type_of_array_content(abs_path_with(rel_path))
got_expected_type = false
# TODO: This needs a better solution
case content_type
when SC_T_NUMBER
got_expected_type = (expected_type == :array or expected_type == :number_array)
value = @driver.get_sc_path_number_array_value(abs_path_with(rel_path))
when SC_T_STRING
got_expected_type = (expected_type == :array or expected_type == :string_array)
value = @driver.get_sc_path_string_array_value(abs_path_with(rel_path))
when SC_T_BOOL
got_expected_type = (expected_type == :array or expected_type == :boolean_array or expected_type == :bool_array)
value = @driver.get_sc_path_boolean_array_value(abs_path_with(rel_path))
when SC_T_HASH
got_expected_type = (expected_type == :array or expected_type == :object_array or expected_type == :hash_array)
value = ObjectArray.new self, rel_path
when SC_T_OBJECT
got_expected_type = (expected_type == :array or expected_type == :object_array)
value = ObjectArray.new self, rel_path
when "empty"
got_expected_type = (expected_type == :array)
value = []
else
got_expected_type = (expected_type == :array)
# TODO: Replace with correct logic. Temporary for now
value = []
end
if (not expected_type.nil?) and (not got_expected_type)
raise UnexpectedTypeError.new(abs_path_with(rel_path), expected_type, SC_T_ARRAY, value)
end
return value
end
end
end
end |
require_relative '../lib/dwelling'
require_relative '../lib/occupant'
require_relative '../lib/modules'
class Apartment < Dwelling
include Modules
attr_reader :address, :city_or_town, :zip_code, :rent, :lease_start_date, :lease_end_date, :space, :objects
def initialize(address, city_or_town, zip_code, rent, lease_start_date, lease_end_date)
super(address, city_or_town, zip_code)
@rent = rent
@lease_start_date = lease_start_date
@lease_end_date = lease_end_date
@space = 5
@objects = []
end
def add_roomate(first_name, last_name)
@space -= 1
@space <= 0 ? "There is no space" : @objects << Occupant.new(first_name, last_name)
end
end
|
require 'generators/feature_box/generator_base'
module FeatureBox
module Generators
class ExistingGenerator < Rails::Generators::NamedBase
include GeneratorBase
desc "Installs FeatureBox to existing application"
def feature_box_install
#name of the User model
@model_name = file_name || "User"
@model_name = @model_name.camelize
#variable for templates
@has_devise = true
#migrate
copy_migrations [/00_.*/,/01_.*/,/02_.*/,/03_.*/,/06_.*/]
rake "db:migrate"
#route
route "mount FeatureBox::Engine => '/feature_box'"
#initializer
template "initializers/initializer.rb", "config/initializers/feature_box.rb"
end
end
end
end
|
class CreateEmployeeTeams < ActiveRecord::Migration
def change
create_table :employee_teams do |t|
t.integer :team_id
t.integer :employee_id
t.timestamps null: false
end
add_index :employee_teams, [:team_id, :employee_id], :unique => true
end
end
|
class OrderItemsController < ApplicationController
skip_before_action :require_login
# before_action :set_order, only: [:ship]
def create
product = Product.find_by(id: params[:order_item][:product_id])
if params[:order_item][:qty].to_i > product.inv_qty
flash[:warning] = "Quantity selected exceeds amount availabe in inventory"
redirect_to product_path(product.id)
elsif @current_order.nil?
@current_order = Order.new
@current_order.save
end
@order_item = @current_order.order_items.new(order_item_params)
@order_item.save
@current_order.save
@current_order.update(status: "Pending")
session[:order_id] = @current_order.id
redirect_to cart_path(@current_order.id)
# else
# flash[:warning] = "Item order not placed"
# redirect_to root_path
# # end
end
def update
product = Product.find_by(id: params[:order_item][:product_id])
if params[:order_item][:qty].to_i > product.inv_qty
flash[:warning] = "Quantity selected exceeds amount available in inventory"
redirect_to product_path(product.id)
else
@order_item = @current_order.order_items.find_by(id: params[:id])
if @order_item.nil?
flash[:warning] = "Order item not found"
redirect_to root_path
else
@order_item.update_attributes(order_item_params)
@current_order.save
if @order_item.save
redirect_to cart_path(@current_order.id)
else
flash[:warning] = "Item order not updated"
redirect_to root_path
end
end
end
end
def cart_direct
product = Product.find_by(id: params[:id])
if product.inv_qty == 0
flash[:warning] = "Product is out of stock"
redirect_to products_path
elsif @current_order.nil?
@current_order = Order.new
@current_order.save
end
@order_item = @current_order.order_items.new(product_id: params[:id], qty: 1, shipped: false)
@order_item.save
@current_order.save
session[:order_id] = @current_order.id
redirect_to cart_path(@current_order.id)
end
def destroy
@order_item = @current_order.order_items.find(params[:id])
@order_item.destroy
@order_items = @current_order.order_items
redirect_to cart_path(@current_order.id)
end
def ship
@order_item = OrderItem.find_by(product_id: params[:id])
@order_item.update(shipped: true)
@order_item.order.check_order_status
if @order_item.save
flash[:success] = 'Item(s) have been marked as shipped'
redirect_back(fallback_location: root_path)
else
flash.now[:warning] = 'Error in shipment status.'
render :show
end
end
private
def order_item_params
params.require(:order_item).permit(:product_id, :qty, :shipped)
end
# def set_order
# @order = current_order
# end
end
|
require 'rubygems'
require 'nokogiri'
require 'resx_template'
ROOT_DIR = 'c:/Andrew/IBA/GDYR/MESPOD/SVN_HG/MESPOD/'
TO_TRANSLATE_CSV = '../../MessagesToTranslate.csv'
TRANSLATED_CSV = '../../TranslatedMessages.csv'
TO_TRANSLATE_CSV_MERGED = 'MessagesToTranslate_merged.csv'
def resources_to_csv
Dir::chdir(ROOT_DIR)
def_lang_list = Hash.new()
# create default (EN) messages list
Dir['**/*.resx'].each do |f_name|
next if f_name.end_with?('de-DE.resx', 'de.resx', 'sl.resx')
File.open(f_name) do |f|
doc = Nokogiri::XML(f)
doc.xpath(("//data[not(@type)]")).each do |node|
name = node['name']
value = node.children()[1].inner_text
def_lang_list[f_name] = [] if not def_lang_list.has_key?(f_name)
def_lang_list[f_name].push([name, value]) if (name.end_with?("Caption", "Text")) or f_name.end_with?("UserMessage.resx", "Resources.resx")
end
end
end
other_lang_list = Hash.new()
# combine default list with other languages translations
res_lang_regexp = /\/\S+\.([^\.]+)\.resx/
Dir['**/*.resx'].each do |f_name|
next if def_lang_list.has_key?(f_name)
match = res_lang_regexp.match(f_name)
next if match.nil?
lang = match[1]
def_lang_f_name = f_name.sub(/([^\.]+)\.resx/, "resx")
File.open(f_name) do |f|
doc = Nokogiri::XML(f)
doc.xpath(("//data[not(@type)]")).each do |node|
name = node['name']
value = node.children()[1].inner_text
other_lang_list[def_lang_f_name + "|" + name] = {} if not def_lang_list.has_key?(def_lang_f_name + "|" + name)
other_lang_list[def_lang_f_name + "|" + name][lang] = value if (name.end_with?("Caption", "Text")) or def_lang_f_name.end_with?("UserMessage.resx", "Resources.resx")
end
end
end
merged_list = {}
# merging two lists
def_lang_list.each_pair do |f_name, val|
val.each do |(name, value)|
langs_map = other_lang_list[f_name + "|" + name]
langs_map = {} if langs_map.nil?
langs_map[:default] = value
merged_list[f_name] = [] if merged_list[f_name].nil?
merged_list[f_name].push([name, langs_map])
end
end
File.open(TO_TRANSLATE_CSV, "w") do |f|
f.write("File name;Resource name;EN;SL\n")
merged_list.each_pair do |f_name, val|
val.each do |(name, langs_map)|
f.write("#{f_name};#{name};#{langs_map[:default]};#{langs_map["sl"]}\n")
end
end
end
return 0
end
def csv_to_resources
hash = Hash.new()
Dir::chdir(ROOT_DIR)
File.open(TRANSLATED_CSV) do |f|
while (line = f.gets)
(res_f, mess_id, _, trans) = line.split(/;/)
hash[res_f] = [] if not hash.has_key?(res_f)
hash[res_f].push([mess_id, trans])
end
end
hash.each_pair do |key, val|
resx_file = key.sub(/resx/, "sl.resx")
File.open(resx_file, "w") do |f|
f.write(ResxTemplate::Start)
val.each do | (mess_id, trans)|
f.write(" <data name=\"#{mess_id}\" xml:space=\"preserve\">\n <value>#{trans}</value>\n </data>\n")
end
f.write(ResxTemplate::End)
end
end
end
def append_translation
hash_by_msg = Hash.new
Dir::chdir(ROOT_DIR)
File.open(TRANSLATED_CSV) do |f|
while (line = f.gets)
(_, _, msg, trans) = line.split(/;/)
hash_by_msg[msg]=trans
end
end
File.open(TO_TRANSLATE_CSV) do |fin|
File.open(TO_TRANSLATE_CSV_MERGED, "w") do |fout|
while (line = fin.gets)
line.sub!(/\n/,"")
(_, _, msg) = line.split(/;/)
trans = ""
trans = hash_by_msg[msg] if hash_by_msg.has_key?(msg)
fout.write(line + ";" + trans + "\n")
end
end
end
end
#append_translation
resources_to_csv
#csv_to_resources
|
#!/usr/bin/env ruby
require './board'
require 'yaml'
class MinesweeperGame
def initialize
mode = choose_mode
@board = Board.new(mode)
@accum_time = 0
end
def play_game
@start_time = Time.now
until @board.game_over?
play_turn
end
@accum_time += Time.now - @start_time
@board.game_feedback(@accum_time.to_i)
end
def play_turn
move = get_move
#move[0]=command, move[1]=row move[2]=column
if move[0] == 's'
@accum_time += Time.now - @start_time
save_game
exit
elsif move[0] == 'f'
@board.flag_bomb(move[1],move[2])
else
@board.reveal(move[1],move[2])
end
end
def save_game
file_name = ""
while true
puts "Enter game file name:"
file_name = gets.chomp
break if file_name.length > 0
end
saved_game = self.to_yaml
File.open(file_name, "w") {|f| f.puts saved_game }
end
def get_move
move = ""
while true
@board.render_board
puts "What would you like to do this turn?"
puts "Please enter 'f' to flag, 'r' to reveal, or 's's to save and quit."
puts "Don't forget to include the coordinates. Example: (f 0 0)"
move = parse_move(gets.chomp.split)
break if move[0] == 's' || move_valid?(move)
puts "The move was either unavailable or formatted incorrectly."
end
move
end
def choose_mode
mode = 0
while true
puts "What size board would you like to play? (small: 1 or large: 2)"
mode = gets.to_i
break if mode == 1 || mode == 2
puts "Invalid input, please choose either 1 or 2"
end
mode
end
#### Private Methods ####
private
def parse_move(move)
if move.count == 1 && move.first.downcase == 's'
[move.first.downcase]
elsif move.count == 3 && move.first.is_a?(String)
[move[0].downcase, move[1].to_i, move[2].to_i]
else
[]
end
end
def move_valid?(move)
return false if move.empty?
return false unless move[0] == 'f' || move[0] == 'r'
@board.space_hidden?(move[1], move[2])
end
end
#### Execution Script ####
if __FILE__ == $PROGRAM_NAME
answer = ""
if ARGV[0]
answer = ARGV.shift
else
while true
puts "Welcome to Minesweeper"
puts "Play new game or load saved game? (ng sg)"
answer = gets.chomp.downcase
break if answer == 'ng' || answer == 'sg'
end
end
if answer == 'ng'
game = MinesweeperGame.new
game.play_game
elsif answer == 'sg'
filename = ""
unless ARGV.empty?
filename = ARGV.shift
else
while true
puts "What is the file called?"
filename = gets.chomp
break unless filename.empty?
end
end
game = YAML::load(File.read(filename))
game.play_game
end
end
|
module Peano
def Recur(&block)
Trampoline.run(block)
end
class Trampoline
def run(&block)
result = block.call
while result.kind_of?(Proc) do
result = result.call
end
result
end
end
end
|
class MissingRelations < ActiveRecord::Migration
def change
create_table :resellers_products do |t|
t.integer :reseller_id
t.integer :products_id
end
create_table :events_partners do |t|
t.integer :event_id
t.integer :partner_id
end
add_column :products, :partner_id, :integer
end
end
|
Pod::Spec.new do |s|
s.name = 'PSPDFKit'
s.version = '10.1.0'
s.homepage = 'https://pspdfkit.com'
s.documentation_url = 'https://pspdfkit.com/guides/ios/current'
s.license = { :type => 'Commercial', :file => 'PSPDFKit.xcframework/LICENSE' }
s.author = { 'PSPDFKit GmbH' => 'support@pspdfkit.com' }
s.summary = 'The Best Way to Handle PDF Documents on iOS.'
s.description = <<-DESC
A high-performance viewer, extensive annotation and document editing tools, digital signatures, and more.
DESC
s.platform = :ios, '12.0'
s.source = { :http => 'https://customers.pspdfkit.com/pspdfkit-ios/10.1.0.zip' }
s.library = 'z', 'sqlite3', 'xml2', 'c++'
s.xcconfig = { 'FRAMEWORK_SEARCH_PATHS' => '"$(PODS_ROOT)/PSPDFKit/**"',
'HEADER_SEARCH_PATHS' => '$(SDKROOT)/usr/include/libxml2' }
s.frameworks = 'QuartzCore', 'CoreText', 'CoreMedia', 'MediaPlayer', 'AVFoundation', 'ImageIO', 'MessageUI',
'CoreGraphics', 'Foundation', 'CFNetwork', 'MobileCoreServices', 'SystemConfiguration',
'Security', 'UIKit', 'AudioToolbox', 'QuickLook', 'CoreTelephony',
'Accelerate', 'CoreImage'
s.requires_arc = true
s.swift_version = '5.0'
s.module_name = 'PSPDFKitSDK'
s.default_subspec = 'Core'
s.subspec 'Core' do |core|
core.preserve_paths = 'PSPDFKit.xcframework', 'PSPDFKit.dSYMs/PSPDFKit.framework.ios-arm64.dSYM', 'PSPDFKit.dSYMs/PSPDFKit.framework.ios-arm64_x86_64-maccatalyst.dSYM', 'PSPDFKit.dSYMs/PSPDFKit.framework.ios-arm64_x86_64-simulator.dSYM'
core.vendored_frameworks = 'PSPDFKit.xcframework'
end
end
|
class Admin::CandidateProfilesController < ApplicationController
before_action :authenticate_user!
layout 'admin'
def index
@candidate_profiles = CandidateProfile.order(created_at: :desc)
end
def show
@candidate_profile = CandidateProfile.find(params[:id])
end
end
|
class AddAreaToTranslationCacheMetaData < ActiveRecord::Migration[5.0]
def change
add_column :translation_cache_meta_data, :area, :string, default: 'dresden'
end
end
|
class Membership < ActiveRecord::Base
include ActiveModel::Transitions
belongs_to :user
belongs_to :company
validates_presence_of :status
state_machine attribute_name: :status do
state :active
end
end
|
namespace :dev do
desc "Configure development environment"
task setup: :environment do
p 'Generating new database'
%x(rails db:drop db:create db:migrate)
p 'Creating Users...'
10.times do |user|
User.create!(
email: Faker::Internet.email,
password: '123456'
)
end
p 'Users were created!'
p 'Creating my admin user'
User.create(email:'admin@adm.com', password: '123456')
p 'Creating Notes...'
100.times do |note|
Note.create!(
title: Faker::BossaNova.artist,
description: Faker::BossaNova.song,
user_id: User.all.sample.id
)
end
p 'Notes were created!'
end
end
|
require 'spec_helper'
# describe OurOneFeature do
describe 'a random user visits the home page' do
it 'should have a field for a user name' do
visit root_path
expect(page).to have_field('username')
end
it 'should have a button to show picture' do
visit root_path
expect(page).to have_button("Get")
end
context 'when the user fills in the field properly and clicks the button' do
it "shows the most recent photo for that user" do
visit root_path
fill_in :username, with: "blairand"
click_on "Get"
expect(page).to have_content "instagram_image_1"
end
end
end
# end
|
class BroProductImage < ActiveRecord::Base
belongs_to :product, class_name: 'BroProduct', foreign_key: 'bro_product_id', touch: true
has_one :bro_sale, through: :product
mount_uploader :file, BasicUploader
mount_uploader :thumbnail, BasicUploader
scope :sorted, -> { order(position: :asc) }
end
|
require 'spec_helper'
describe RouteLocalize do
let(:args) { [app, conditions, requirements, defaults, as, anchor, route_set] }
let(:app) { double(:app) }
let(:conditions) { { required_defaults: [:localize], path_info: "/bang" } }
let(:requirements) { [:localize] }
let(:defaults) { {} }
let(:as) { "bang" }
let(:anchor) { double(:anchor) }
let(:route_set) { double(:route_set, named_routes: named_routes) }
let(:named_routes) { double(:named_routes, routes: {}, module: route_module) }
let(:route_module) { double(:module, define_method: nil) }
describe '.translate_route' do
context "with no localization" do
let(:defaults) { { foo: "bar" } }
it "yields once" do
expect { |b| RouteLocalize.translate_route(*args, &b) }.to \
yield_control.once
end
it "yields the given args except for route_set" do
expected_args = [app, conditions, requirements, defaults, as, anchor]
expect { |b| RouteLocalize.translate_route(*args, &b) }.to \
yield_with_args(*expected_args)
end
it "does not define locale helpers" do
RouteLocalize.translate_route(*args) { }
expect(route_module).not_to have_received(:define_method)
end
end
context "with localize by subdomain" do
let(:defaults) { { localize: [:en, :fr] } }
it "yields twice" do
expect { |b| RouteLocalize.translate_route(*args, &b) }.to \
yield_control.twice
end
it "defines path and url helpers" do
RouteLocalize.translate_route(*args) { }
expect(route_module).to have_received(:define_method).twice
expect(route_module).to have_received(:define_method).with("bang_path")
expect(route_module).to have_received(:define_method).with("bang_url")
end
end
end
describe '.define_locale_helpers' do
let(:helper) { double(:helper, define_method: nil) }
before do
# Spy on the generated methods beeing called
RSpec::Mocks.configuration.verify_partial_doubles = false
allow(RouteLocalize).to receive(:bang_fr_url)
allow(RouteLocalize).to receive(:bang_fr_path)
allow(RouteLocalize).to receive(:bang_en_url)
allow(RouteLocalize).to receive(:bang_en_path)
# Store the methods defined
@bang_path = @bang_url = nil
expect(helper).to receive(:define_method).with("bang_path") { |&m| @bang_path = m }
expect(helper).to receive(:define_method).with("bang_url") { |&m| @bang_url = m }
end
it "defines path in each locale" do
RouteLocalize.define_locale_helpers("bang", helper)
I18n.locale = :fr
@bang_path.call
expect(RouteLocalize).to have_received(:bang_fr_path).once
I18n.locale = :en
@bang_path.call
expect(RouteLocalize).to have_received(:bang_en_path).once
end
it "defines methods that call the path and url of the current locale" do
RouteLocalize.define_locale_helpers("bang", helper)
# When in french, call the french methods
I18n.locale = :fr
@bang_path.call
expect(RouteLocalize).to have_received(:bang_fr_path).once
@bang_url.call
expect(RouteLocalize).to have_received(:bang_fr_url).once
# When in english, call the english methods
I18n.locale = :en
@bang_path.call
expect(RouteLocalize).to have_received(:bang_en_path).once
@bang_url.call
expect(RouteLocalize).to have_received(:bang_en_url).once
end
end
end
|
class UsersController < ApplicationController
def index
@users = params[:ids] ?
User.where(id: params[:ids].split(",")).to_a :
User.all.to_a
end
def create_or_replace
if user = User.find_by( id: params[:id] )
replacement= User.new(
user_params.merge( id: params[:id] )
)
if replacement.valid?
user.destroy
replacement.save
head :no_content
else
head :unprocessable_entity
end
else
if user = User.create(
user_params.merge( id: params[:id] )
)
render json: user, status: :created
else
head :unprocessable_entity
end
end
end
def update
if user = User.find_by( id: params[:id] )
if user.update_attributes( user_params )
head :no_content
else
head :unprocessable_entity
end
else
head :not_found
end
end
def destroy
if user = User.find_by( id: params[:id] )
if user.destroy
head :no_content
else
head :internal_server_error
end
else
head :not_found
end
end
protected
def user_params
params.require(:user).permit( :title, :body )
end
end
|
class Api::V1::AboutmesController < Api::V1::BaseController
def index
user = current_user
aboutme = user.aboutme
render json: aboutme, status: 200
end
end |
require 'rails_helper'
RSpec.describe 'Merchants Show API' do
before :each do
FactoryBot.reload
end
describe 'happy path' do
it 'fetch one merchant by id' do
merchant1 = create(:merchant)
get "/api/v1/merchants/#{merchant1.id}"
expect(response).to be_successful
merchant = JSON.parse(response.body, symbolize_names: true)
expect(merchant.count).to eq(1)
expect(merchant[:data]).to have_key(:id)
expect(merchant[:data][:id]).to be_a(String)
expect(merchant[:data]).to have_key(:type)
expect(merchant[:data][:type]).to be_a(String)
expect(merchant[:data]).to have_key(:attributes)
expect(merchant[:data][:attributes]).to be_a(Hash)
expect(merchant[:data][:attributes]).to have_key(:name)
expect(merchant[:data][:attributes][:name]).to be_a(String)
end
end
describe 'sad path' do
it 'bad integer id returns 404' do
get "/api/v1/merchants/623"
expect(response).to_not be_successful
expect(response).to have_http_status(404)
error = JSON.parse(response.body, symbolize_names: true)[:error]
expect(error).to eq("Couldn't find Merchant with 'id'=623")
end
end
end
|
# The model has already been created by the framework, and extends Rhom::RhomObject
# You can add more methods here
require 'json'
class Product
include Rhom::PropertyBag
# Uncomment the following line to enable sync with Product.
# enable :sync
property :name, :string
property :brand, :string
property :price, :string
def self.metadata=(json)
db = ::Rho::RHO.get_src_db(get_source_name)
db.start_transaction
db.execute_sql(
"UPDATE sources set metadata=? where name=?", json, get_source_name
)
db.commit
end
def self.generate_metadata
# define the metadata
row1 = {
:label => 'Address 1',
:value => '123 fake street',
:name => 'address1',
:type => 'labeledrow'
}
table = {
:label => 'Table',
:type => 'table',
:children => [ row1, row1, row1 ]
}
view = {
:title => 'UI meta panel',
:type => 'view',
:children => [table]
}
# return the definition as JSON
{'index_meta' => view}.to_json
end
#add model specifc code here
end
|
class Role < ApplicationRecord
has_many :research_users
has_many :users, through: :research_users
validates :name, presence: { message: "Nombre no puede ir vacio" },
uniqueness: { case_sensitive: false, message: "Ya hay otro rol con el mismo nombre" }
def self.get_default_role
where(is_default: true).first
end
def self.all_roles
roles = self.all.order(name: :asc)
end
end |
require 'spec_helper'
RSpec.describe Role do
it { is_expected.to belong_to(:team) }
it { is_expected.to belong_to(:user) }
it { is_expected.to validate_presence_of(:user) }
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_inclusion_of(:name).in_array(Role::ROLES) }
it { is_expected.to validate_uniqueness_of(:user_id).scoped_to([:team_id, :name]) }
describe 'application' do
it 'includes role name' do
FactoryGirl.create(:student_role)
expect(Role.includes?('student')).to eq true
end
end
context 'with callbacks' do
context 'before save' do
before { allow(subject).to receive(:valid?) { true } }
it 'creates a confirmation token' do
expect { subject.save }.to \
change { subject.confirmation_token }.from nil
end
end
end
describe '#state' do
let(:user) { FactoryGirl.create(:user) }
let(:team) { FactoryGirl.create(:team) }
before do
subject
end
subject do
user.roles.create team: team, name: role_name
end
context 'when the user is added as a coach' do
let(:role_name) { 'coach' }
it 'has the pending state' do
expect(subject).to be_pending
end
end
context 'when the user is added as a student' do
let(:role_name) { 'student' }
it 'has the confirmed state' do
expect(subject).to be_confirmed
end
end
context 'when the user is added as a mentor' do
let(:role_name) { 'mentor' }
it 'has the confirmed state' do
expect(subject).to be_confirmed
end
end
context 'when the user is added as a supervisor' do
let(:role_name) { 'supervisor' }
it 'has the confirmed state' do
expect(subject).to be_confirmed
end
end
end
describe 'create' do
let(:user) { FactoryGirl.create(:user) }
let(:team) { FactoryGirl.create(:team) }
let(:mailer) { double('RoleMailer') }
before do
allow(RoleMailer).to receive(:user_added_to_team).and_return(mailer)
allow(mailer).to receive(:deliver_later)
subject
end
shared_examples 'a guide role' do
it 'sends a notification to the user' do
expect(RoleMailer).to have_received(:user_added_to_team).with(subject)
expect(mailer).to have_received(:deliver_later)
end
end
subject do
user.roles.create team: team, name: role_name
end
context 'when the user is added as a student' do
let(:role_name) { 'student' }
it 'does not send a notification' do
expect(RoleMailer).to_not have_received(:user_added_to_team).with(subject)
end
end
context 'when the user is added as a coach' do
let(:role_name) { 'coach' }
it_behaves_like 'a guide role'
end
context 'when the user is added as a mentor' do
let(:role_name) { 'mentor' }
it_behaves_like 'a guide role'
end
end
end
|
class Post < ActiveRecord::Base
has_many :comments, dependent: :destroy
has_many :images, dependent: :destroy
validates :title, presence: true
validates :text, presence: true
validates :author, presence: true
accepts_nested_attributes_for :images,
reject_if: proc { |attributes| attributes["filename"].blank? },
allow_destroy: true
accepts_nested_attributes_for :comments
def is_published?
published
end
def created_at_pretty
created_at.strftime("<strong>%Y-%m-%d</strong>").html_safe
end
end
|
class Order < ApplicationRecord
# belongs_to :account
has_many :order_items
before_save :update_total
before_create :update_status
def calculate_total
self.order_items.collect { |item| item.product.price * item.quantity }.sum
end
def total_items
self.order_items.collect { |item| item.quantity }.sum
end
def check_duplicate(order_item)
# binding.pry
if self.order_items.first.id?
cart_items = self.order_items
cart_items.each do |item|
if item.product_id == order_item.product_id
item.quantity += order_item.quantity
item.save
order_item.destroy
else
return self
end
end
else
return self
end
end
private
def update_status
if self.status == nil?
self.status = "In progress"
end
end
def update_total
self.totalPrice = calculate_total
end
end
|
module StyleGuide
class JavaScript < Base
DEFAULT_CONFIG_FILENAME = "javascript.json"
def file_review(commit_file)
FileReview.new(filename: commit_file.filename) do |file_review|
Jshintrb.lint(commit_file.content, config).compact.each do |violation|
line = commit_file.line_at(violation["line"])
file_review.build_violation(line, violation["reason"])
end
file_review.complete
end
end
def file_included?(commit_file)
!excluded_files.any? do |pattern|
File.fnmatch?(pattern, commit_file.filename)
end
end
private
def config
custom_config = repo_config.for(name)
if custom_config["predef"].present?
custom_config["predef"] |= default_config["predef"]
end
default_config.merge(custom_config)
end
def excluded_files
repo_config.ignored_javascript_files
end
def default_config
config_file = File.read(default_config_file)
JSON.parse(config_file)
end
def default_config_file
DefaultConfigFile.new(
DEFAULT_CONFIG_FILENAME,
repository_owner_name
).path
end
def name
"javascript"
end
end
end
|
require 'set'
class Character < ApplicationRecord
has_and_belongs_to_many :story
belongs_to :user
has_many :relationships
has_many :follower_relationships, foreign_key: :character2, class_name: 'Relationship'
has_many :followers, through: :follower_relationships, source: :follower
has_many :following_relationships, foreign_key: :character_id, class_name: 'Relationship'
has_many :following, through: :following_relationships, source: :following
has_many :quality
def characterRelationship
@relationship = Relationship.where('character_id = ? or character2 = ?', self.id, self.id)
relationHash = {}
@relationship.each do |relation|
@character = Character.where(id: relation.character_id)[0]
charName = @character.name.to_s
if charName == self.name
@character = Character.where(id: relation.character2)[0]
if @character != nil
@relation = relation
charName = @character.name.to_s
relationHash[charName] = @relation
end
elsif charName != self.name
if @character != nil
@relation = relation
relationHash[charName] = @relation
end
end
end
return relationHash
end
def notRelated
@relationship = characterRelationship.keys
@allCharacters = Character.where.not(id: self.id)
@notRelated = @allCharacters.select do |x|
!@relationship.include?(x.name)
end
return @notRelated
end
def destroyRelation
@exist = Relationship.where(character_id: self.id).or(Relationship.where(character2: self.id))
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 rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
10.times do
description = FFaker::Lorem.sentence(2)
name = FFaker::Vehicle.model
Item.create!(name: name, description: description, need_authorize: false)
end
10.times do
name = FFaker::Vehicle.model
@item = Item.find(1)
Stock.create!(name: name, is_on_loan: false, item_id: 1)
end |
module MacRubyScreencastsHelper
Screencast = Struct.new(:date, :name, :href, :author, :company)
def macruby_screencasts
[
Screencast.new("2010-04-10", "Introduction to MacRuby and HotCocoa", "http://thinkcode.tv/catalog/introduction-macruby/", "Renzo Borgatti", "ThinkCode.TV"),
Screencast.new("2009-11-10", "Introduzione a MacRuby e HotCocoa (Italian)", "http://it.thinkcode.tv/catalogo/introduzione-a-macruby-e-hotcocoa/", "Renzo Borgatti", "ThinkCode.TV"),
Screencast.new("2009-05-19", "Meet MacRuby", "http://peepcode.com/products/meet-macruby", "Geoffrey Grosenbach", "Peepcode"),
Screencast.new("2009-05-19", "MacRuby Presentation (Free)", "http://nubyonrails.com/articles/macruby-presentation-from-rubyfest", "Geoffrey Grosenbach", "Peepcode"),
Screencast.new("2009-05-05", "MacRuby - Bonus Track (Free)", "http://pragmaticstudio.com/screencasts/6-macruby", "Mike Clark", "Pragmatic Studio"),
Screencast.new("2009-05-11", "Embedding MacRuby - Bonus track (Free)", "http://pragmaticstudio.com/screencasts/7-embedding-macruby", "Mike Clark", "Pragmatic Studio")
]
end
end
Webby::Helpers.register(MacRubyScreencastsHelper) |
require 'active_support/core_ext/string'
require 'builder'
module OWD
class Document
def initialize attributes = {}
@attributes = attributes
@doc = Builder::XmlMarkup.new
end
def owd_name
"OWD_%s_REQUEST" % self.class.name.split('::').last.underscore.upcase
end
def build opts = {}
doc.instruct!(:xml, :encoding => 'UTF-8')
doc.OWD_API_REQUEST(@attributes) do
self._build(opts)
end
doc.target!
end
private
def doc
@doc
end
end
class SimpleInlineDocument
def _build opts = {}
doc.tag!(self.owd_name, opts)
end
end
end
Dir[File.dirname(__FILE__) + "/documents/*.rb"].each do |file|
require file
end
|
# question_9.rb
flintstones = { "Fred" => 0, "Wilma" => 1, "Barney" => 2, "Betty" => 3, "BamBam" => 4, "Pebbles" => 5 }
# There are two elements to this
# 1. Removing all the key value pairs except for "Barney" => 2
# 2. Changing the resulting hash into an array
# For the first part we could use keep_if or select and for the second part flatten
flintstones = flintstones.keep_if { |k, v| k == "Barney" }.flatten
flintstones = flintstones.select { |k, v| k == "Barney" }.flatten |
class Api::BooksController < ApplicationController
before_action :require_signed_in!
def reviews
@book = Book.find(params[:id])
render :reviews
end
def create
isbn = book_params['isbn']
@book = Book.find_by_isbn(isbn)
if @book
render :show
else
@book = Book.new(book_params)
if @book.save
render :show
else
render json: @book.errors, status: :unprocessable_entity
end
end
end
def show
@book = Book.find(params[:id])
render :show
end
private
def book_params
params.require(:book).permit(:title, :author, :cover_image_url,
:synopsis, :number_of_pages, :isbn)
end
end
|
class BootstrapAttributeTableResourceRenderer < AttributeTableResourceRenderer
private
def table_html_options
{ class: 'table table-responsive table-condensed table-striped table-hover' }
end
end
|
RSpec.configure do |config|
config.before(:all, type: :request) do
host! 'api.example.com'
end
end
module RequestHelpers
def json_headers
{
'Accept' => 'application/json',
'Content-Type' => 'application/json',
}
end
def json
return if response.body.blank?
Oj.load(response.body, symbol_keys: true)
end
def json_post(url, params: {}, headers: {}, basic_auth: false, auth: false, auth_user: nil)
post url, params: params, as: :json, headers: prepare_headers(headers, auth, auth_user, basic_auth)
end
def json_get(url, params: {}, headers: {}, basic_auth: false, auth: false, auth_user: nil)
get url, params: params, headers: prepare_headers(headers, auth, auth_user, basic_auth)
end
def json_put(url, params: {}, headers: {}, basic_auth: false, auth: false, auth_user: nil)
put url, params: params, as: :json, headers: prepare_headers(headers, auth, auth_user, basic_auth)
end
def json_delete(url, params: {}, headers: {}, basic_auth: false, auth: false, auth_user: nil)
delete url, params: params.to_json, headers: prepare_headers(spec_headers, auth, auth_user, basic_auth)
end
def prepare_headers(spec_headers, auth, auth_user, basic_auth)
headers = spec_headers.reverse_merge(json_headers)
headers.reverse_merge!(http_login(basic_auth)) if basic_auth.present?
headers
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.