text stringlengths 10 2.61M |
|---|
class Bot::Alegre < BotUser
check_settings
::ProjectMedia.class_eval do
attr_accessor :alegre_similarity_thresholds
end
def self.run(body)
if CONFIG['alegre_host'].blank?
Rails.logger.warn("[Alegre Bot] Skipping events because `alegre_host` config is blank")
return false
end
handled = false
begin
pm = ProjectMedia.where(id: body.dig(:data, :dbid)).last
if body.dig(:event) == 'create_project_media' && !pm.nil?
self.get_language(pm)
self.send_to_image_similarity_index(pm)
self.send_to_title_similarity_index(pm)
self.get_flags(pm)
handled = true
end
rescue StandardError => e
Rails.logger.error("[Alegre Bot] Exception for event `#{body['event']}`: #{e.message}")
self.notify_error(e, { bot: self.name, body: body }, RequestStore[:request])
end
handled
end
def self.get_language(pm)
lang = pm.text.blank? ? 'und' : self.get_language_from_alegre(pm.text)
self.save_language(pm, lang)
lang
end
def self.get_language_from_alegre(text)
lang = 'und'
begin
response = self.request_api('get', '/text/langid/', { text: text })
lang = response['result']['language']
rescue
end
lang
end
def self.save_language(pm, lang)
self.save_annotation(pm, 'language', { language: lang })
end
def self.save_annotation(pm, type, fields)
annotation = Dynamic.new
annotation.annotated = pm
annotation.annotator = BotUser.where(login: 'alegre').first
annotation.annotation_type = type
annotation.disable_es_callbacks = Rails.env.to_s == 'test'
annotation.set_fields = fields.to_json
annotation.skip_check_ability = true
annotation.save!
annotation
end
def self.get_flags(pm, attempts = 0)
return if pm.report_type != 'uploadedimage'
begin
result = self.request_api('get', '/image/classification/', { uri: self.media_file_url(pm) })
self.save_annotation(pm, 'flag', result['result'])
rescue
sleep 1
self.get_flags(pm, attempts + 1) if attempts < 5
end
end
def self.media_file_url(pm)
# FIXME Ugly hack to get a usable URL in docker-compose development environment.
ENV['RAILS_ENV'] != 'development' ? pm.media.file.file.public_url : "#{CONFIG['storage']['endpoint']}/#{CONFIG['storage']['bucket']}/#{pm.media.file.file.path}"
end
def self.send_to_title_similarity_index(pm)
return if pm.title.blank?
self.send_to_text_similarity_index(pm, 'title', pm.title)
end
def self.send_to_text_similarity_index(pm, field, text)
self.request_api('post', '/text/similarity/', {
text: text,
context: {
team_id: pm.team_id,
field: field,
project_media_id: pm.id
}
})
end
def self.send_to_image_similarity_index(pm)
return if pm.report_type != 'uploadedimage'
self.request_api('post', '/image/similarity/', {
url: self.media_file_url(pm),
context: {
team_id: pm.team_id,
project_media_id: pm.id
}
})
end
def self.request_api(method, path, params = {})
uri = URI(CONFIG['alegre_host'] + path)
klass = 'Net::HTTP::' + method.capitalize
request = klass.constantize.new(uri.path, 'Content-Type' => 'application/json')
request.body = params.to_json
http = Net::HTTP.new(uri.hostname, uri.port)
http.use_ssl = uri.scheme == 'https'
begin
response = http.request(request)
JSON.parse(response.body)
rescue StandardError => e
Rails.logger.error("[Alegre Bot] Alegre error: #{e.message}")
self.notify_error(e, { bot: self.name, url: uri, params: params }, RequestStore[:request] )
{ 'type' => 'error', 'data' => { 'message' => e.message } }
end
end
def self.get_items_with_similar_title(pm, threshold)
self.get_items_with_similar_text(pm, 'title', threshold, pm.title)
end
def self.extract_project_medias_from_context(context)
# We currently have two cases of context:
# - a straight hash with project_media_id
# - an array of hashes, each with project_media_id
pms = []
if context.kind_of?(Array)
context.each{ |c| pms.push(c.with_indifferent_access.dig('project_media_id')) }
elsif context.kind_of?(Hash)
pms.push(context.with_indifferent_access.dig('project_media_id'))
end
pms
end
def self.get_items_with_similar_text(pm, field, threshold, text)
similar = self.request_api('get', '/text/similarity/', {
text: text,
context: {
team_id: pm.team_id,
field: field
},
threshold: threshold
})
similar.dig('result')&.collect{ |r| self.extract_project_medias_from_context(r.dig('_source', 'context')) }.flatten.reject{ |id| id.blank? }.map(&:to_i).uniq.sort - [pm.id]
end
def self.get_items_with_similar_image(pm, threshold)
similar = self.request_api('get', '/image/similarity/', {
url: self.media_file_url(pm),
context: {
team_id: pm.team_id,
},
threshold: threshold
})
similar.dig('result')&.collect{ |r| self.extract_project_medias_from_context(r.dig('context')) }.flatten.reject{ |id| id.blank? }.map(&:to_i).uniq.sort - [pm.id]
end
def self.add_relationships(pm, pm_ids)
return if pm_ids.blank? || pm_ids.include?(pm.id)
# Take first match as being the best potential parent.
# Conditions to check for a valid parent in 2-level hierarchy:
# - If it's a child, get its parent.
# - If it's a parent, use it.
# - If it has no existing relationship, use it.
parent_id = pm_ids[0]
source_ids = Relationship.where(:target_id => parent_id).select(:source_id).distinct
if source_ids.length > 0
# Sanity check: if there are multiple parents, something is wrong in the dataset.
Rails.logger.error("[Alegre Bot] Found multiple relationship parents for ProjectMedia #{parent_id}") if source_ids.length > 1
# Take the first source as the parent.
parent_id = source_ids[0].source_id
end
# Better be safe than sorry.
return if parent_id == pm.id
r = Relationship.new
r.skip_check_ability = true
r.relationship_type = { source: 'parent', target: 'child' }
r.source_id = parent_id
r.target_id = pm.id
r.save!
end
end
|
module Decorator
def decorate_method(fn, &block)
fxn = instance_method(fn)
define_method fn do |*args|
instance_exec(fxn.bind(self), *args, &block)
end
rescue NameError, NoMethodError
fxn = singleton_class.instance_method(fn).bind(self)
define_singleton_method fn do |*args|
instance_exec(fxn, *args, &block)
end
end
end
module Memoizer
include Decorator
def memoize(fn, cache: Hash.new{|h,k|h[k]={}})
decorate_method(fn) do |meth, *args|
unless cache[self].include?(args)
cache[self][args] = meth.call(*args)
end
cache[self][args]
end
end
alias :memo :memoize
end
|
class AddCatalogToProduct < ActiveRecord::Migration
def self.up
add_column :products, :catalog, :string
end
def self.down
remove_column :products, :catalog
end
end
|
class Tree
attr_accessor :children, :node_name
def initialize(name, children=[])
@children = children
@node_name = name
end
def visit_all(&block)
visit &block
# visit(&block)
children.each { |c| c.visit_all &block }
# @children.each { |c| c.visit_all(&block) }
end
def visit(&block)
block.call self
end
end
ruby_tree = Tree.new("Family", [Tree.new("Papa"), Tree.new("Mama")])
puts "Visiting a node"
ruby_tree.visit { |node| puts node.node_name }
puts
puts "Visiting entire tree"
ruby_tree.visit_all { |node| puts node.node_name }
|
module DeviseHelper
def resource_name
:user
end
def resource
@resource ||= User.new
end
def devise_mapping
@devise_mapping ||= Devise.mappings[:user]
end
def devise_error_messages!
return "" unless devise_error_messages?
resource.errors.full_messages.each do |message|
flash_message :danger, message
end
end
def devise_error_messages?
!resource.errors.empty?
end
def devise_messages
devise_error_messages!
end
end |
class Owner < ApplicationRecord
validates :name, presence: true, length: { minimum: 5, message: "Precisa ter no mínimo 5 letras" }
validates :email, presence: true, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
end
|
class TagsController < ApplicationController
before_action :signed_in_user
before_action :set_tag, only: [:show, :edit, :update, :destroy]
# GET /tags
# GET /tags.json
def index
@tags = current_user.tags.all
@tags_groups ={}
StuffsTag::tags_groups(current_user).each do |st|
@tags_groups[st.tag_id] =st.tag_num
end
end
# GET /tags/1
# GET /tags/1.json
def show
end
# GET /tags/new
def new
@tag = current_user.tags.build
end
# GET /tags/1/edit
def edit
end
# POST /tags
# POST /tags.json
def create
@tag = current_user.tags.build(tag_params)
respond_to do |format|
if @tag.save
format.html { redirect_to @tag, notice: 'Tag was successfully created.' }
format.json { render action: 'show', status: :created, location: @tag }
else
format.html { render action: 'new' }
format.json { render json: @tag.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /tags/1
# PATCH/PUT /tags/1.json
def update
respond_to do |format|
if @tag.update(tag_params)
format.html { redirect_to @tag, notice: 'Tag was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @tag.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tags/1
# DELETE /tags/1.json
def destroy
#is tags empty?
@stuffs = StuffsTag.find_by(tag_id: @tag.id)
if @stuffs == nil
flash[:soccuss] ='this tag is delete!'
@tag.destroy
else
flash[:soccuss] ='tag is not empty!'
end
respond_to do |format|
format.html { redirect_to tags_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_tag
@tag = Tag.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def tag_params
params.require(:tag).permit(:name)
end
end
|
module Memflash
class << self
attr_accessor :threshold
end
self.threshold = 300 # Messages longer than this will be stored in Rails.cache
module CachingLayer
def []=(key, value)
value_for_hash = value
if value.kind_of?(String) && value.length >= Memflash.threshold
value_for_hash = memflash_key(key)
Rails.cache.write(value_for_hash, value)
end
super(key, value_for_hash)
end
def [](key)
value_in_hash = super
if memflashed?(key, value_in_hash)
Rails.cache.read(value_in_hash)
else
value_in_hash
end
end
private
def memflash_key(hash_key)
"Memflash-#{hash_key}-#{Time.now.to_f}-#{Kernel.rand}"
end
def memflashed?(key, value)
!!(value =~ /^Memflash-#{key}/)
end
end
end
require 'action_dispatch'
ActionDispatch::Flash::FlashHash.prepend Memflash::CachingLayer
|
# encoding: UTF-8
class SessionsController < ApplicationController
before_action :public_access, only: [:new, :create_with_omniauth]
def new
render layout: "pages"
end
def new_slack
render layout: "pages"
end
def create
user = User.find_by(email: params[:email].downcase)
if user && user.password? && !user.suspended? && user.password_digest && user.authenticate(params[:password])
sign_in(user)
redirect_to signed_in_root_path
else
redirect_to login_path, flash: { error: "No se pudo realizar la autenticación. Revisa tus credenciales e intenta nuevamente. Asegúrate que tu cuenta esté activa y puedas acceder con contraseña. Comunícate con nosotros a info@makeitreal.camp si tienes alguna duda." }
end
end
def create_with_omniauth
if request.env['omniauth.auth'].info.email.blank?
url_omniauth_failure("No pudimos obtener el email de #{request.env['omniauth.auth'].provider.capitalize}. Por favor habilítalo")
elsif user = AuthProvider.omniauth(request.env['omniauth.auth'])
sign_in(user)
redirect_to signed_in_root_path
else
redirect_to login_slack_path, flash: { error:
%Q(No se pudo realizar la autenticación. Si aún no eres estudiante de Make it Real
visita <a href="http://www.makeitreal.camp">makeitreal.camp</a> para conocer nuestros
programas. De lo contrario comunícate con nosotros a info@makeitreal.camp)
}
end
end
def omniauth_failure
url_omniauth_failure("Es necesario que autorices los permisos para poder ingresar a Make it Real.")
end
def destroy
sign_out
redirect_to root_path
end
private
def url_omniauth_failure(message)
redirect_to login_slack_path, flash: { error: message }
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Scn.create(:name => "All England", :value => 47)
Scn.create(:name => "Cheshire and Merseyside", :value => 48)
Scn.create(:name => "East Midlands", :value => 47)
Scn.create(:name => "East of England", :value => 46)
Scn.create(:name => "Greater Manchester", :value => 50)
Scn.create(:name => "North and East London", :value => 50)
Scn.create(:name => "North West and South London", :value => 48)
Scn.create(:name => "Northern England", :value => 48)
Scn.create(:name => "South East Coast", :value => 47)
Scn.create(:name => "South West", :value => 46)
Scn.create(:name => "Thames Valley", :value => 44)
Scn.create(:name => "Wessex", :value => 47)
Scn.create(:name => "West Midlands", :value => 43)
Scn.create(:name => "Yorkshire and the Humber", :value => 53) |
module HttpsResponseHelper
def self.data_not_found
return :status => :not_found,
:json => {
:status => false,
:displayMessage => [{ "message": "Data Not Fund" }],
}
end
def self.errors(errors)
return :status => :unprocessable_entity,
:json => {
:status => false,
:displayMessage => errors,
}
end
def self.deleted_successfully
return :status => :accepted,
:json => {
:status => true,
:data => [{ "message": "Data Deleted Successfully" }],
}
end
end
|
class FilesController < ApplicationController
before_filter :set_dir
def index
@info = get_file_info(@full_path)
if @info[:directory?]
@files = get_files(@full_path)
else
send_file(@full_path)
return
end
respond_to do |format|
format.html
format.json { render_json @files }
end
end
private
def get_files(full_path)
files = []
Dir.foreach(full_path) do |n|
fn = full_path + "/" + n
file_info = get_file_info(fn)
files << file_info if file_info
end
files
end
def get_file_info(full_path)
if File.exists?(full_path)
name = File.basename full_path
is_directory = File.directory?(full_path)
mtime = File.mtime(full_path)
extname = File.extname(full_path).downcase.gsub('.', '')
target_path = full_path[PATH_CONFIG["base_path"].size-1..-1]
target_path = "/" if target_path == ""
basename = File.basename full_path, ".#{extname}"
info = { :name => name,
:directory? => is_directory,
:mtime => mtime,
:extname => extname,
:target_path => target_path,
:basename => basename }
end
end
end
|
FactoryGirl.define do
factory :person do |f|
f.name "John Smith"
sequence(:email) { |i| "email_#{i}@email.com" }
f.org "Sample Organization"
end
factory :invalid_person, parent: :person do |f|
f.email nil
end
end
|
source 'https://rubygems.org'
gem 'puma'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.6'
# Use PostgreSQL as the database for Active Record.
gem 'pg', '0.18.4'
# Use SCSS for stylesheets.
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets.
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views.
gem 'coffee-rails', '~> 4.1.0'
# Use jquery as the JavaScript library.
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster.
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Review parser for iOS and Android.
gem 'criticism', git: "https://62df58300f22dd01f441acec72bf578d9086d52f:x-oauth-basic@github.com/marcferna/criticism.git", branch: 'master'
# Flexible authentication solution.
gem 'devise'
# Sass-powered version of Bootstrap 3.
gem 'bootstrap-sass', '~> 3.3.6'
# Font-Awesome web fonts and stylesheets.
gem 'font-awesome-rails'
# Decorators/View-Models.
gem 'draper'
# A simple wrapper to send notifications to Slack webhooks.
gem 'slack-notifier'
# Manage Procfile-based applications.
gem 'foreman'
# Redis-backed Ruby library for creating background jobs.
gem 'resque'
# Rails-based web interface to Resque
gem 'resque-web', require: 'resque_web'
# A light-weight job scheduling system built on top of resque.
gem 'resque-scheduler'
# Tabs in the Resque Web gem for the Resque Scheduler plugin
gem 'resque-scheduler-web'
# Makes running your Rails app easier. Based on the ideas behind 12factor.net
gem 'rails_12factor'
group :development, :test do
# Debugger
gem 'byebug'
# Loads environment variables from `.env`.
gem 'dotenv-rails'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# Keeps your application running in the background.
gem 'spring'
# A Ruby static code analyzer, based on the community Ruby style guide.
gem 'rubocop', require: false
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Product.delete_all
Product.create!(title: 'Full Zip Jacket',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/FullZipSweatshirtJacket.jpg',
category_id: '1'
)
# . . .
Product.create!(title: 'Hooded Sweatshirt',
description:
%{<p>
Lorem Ipsum is simpnot only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/HoodedSweatshirt.jpg',
category_id: '1',
thumb: 'products/Hoodies.jpg'
)
# . . .
Product.create!(title: 'Polo',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/polos.jpg',
category_id: '1'
)
# . . .
Product.create!(title: 'Flashlight',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/flashlight.jpg',
category_id: '5',
thumb: 'products/IMG_1400.jpg',
thumbtwo: 'products/IMG_1402.jpg'
)
# . . .
Product.create!(title: 'Radio Flashlight',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/RadioFlashlight.jpg',
category_id: '5',
thumb: 'products/IMG_1368.jpg',
thumbtwo: 'products/IMG_1371.jpg',
thumbthree: 'products/IMG_1374.jpg'
)
# . . .
Product.create!(title: 'Stand Light',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/standlight.jpg',
category_id: '5',
thumb: 'products/IMG_1358.jpg'
)
# . . .
Product.create!(title: 'Headset',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/headset.jpg',
category_id: '8',
thumb: 'products/IMG_1502.jpg'
)
# . . .
Product.create!(title: 'ID Card Holder',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/id-card-holders.jpg',
category_id: '4'
)
# . . .
Product.create!(title: 'ID Sleeve',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/Desktop35.jpg',
category_id: '4'
)
# . . .
Product.create!(title: 'Lanyard',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/lanyard.jpg',
category_id: '4',
thumb: 'products/IMG_1398.jpg',
thumbtwo: 'products/IMG_1427.jpg',
thumbthree: 'products/IMG_1435.jpg'
)
# . . .
Product.create!(title: 'USB Pen',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/usb-pen.jpg',
category_id: '6'
)
# . . .
Product.create!(title: 'Powerbank',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/powerbank.jpg',
category_id: '7',
thumb: 'products/IMG_1405.jpg',
thumbtwo: 'products/IMG_1365.jpg'
)
# . . .
Product.create!(title: 'Car Charger',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/carcharger.jpg',
category_id: '7',
thumb: 'products/IMG_1483.jpg',
thumbtwo: 'products/IMG_1484.jpg',
thumbthree: 'products/IMG_1518.jpg'
)
# . . .
Product.create!(title: 'Powerbank with Cables',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/cables.jpg',
category_id: '7',
thumb: 'products/IMG_1545.jpg'
)
# . . .
Product.create!(title: 'Dog Tags',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/dogtags.jpg',
category_id: '8',
thumb: 'products/084.jpg',
thumbtwo: 'products/082.jpg',
thumbthree: 'products/IMG_1378.jpg'
)
# . . .
Product.create!(title: 'Bracelet',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/bracelet.jpg',
category_id: '8',
thumb: 'products/IMG_1450.jpg'
)
# . . .
Product.create!(title: 'Tablet Cover',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/cover.jpg',
category_id: '8',
thumb: 'products/IMG_1508.jpg'
)
# . . .
Product.create!(title: 'Pins',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/pins-zoom.jpg',
category_id: '8',
thumb: 'products/pins.jpg'
)
# . . .
Product.create!(title: 'Pen & Case',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/pen-case.jpg',
category_id: '6',
thumb: 'products/IMG_1472.jpg',
thumbtwo: 'products/IMG_1465.jpg',
thumbthree: 'products/IMG_1454.jpg'
)
# . . .
Product.create!(title: 'USB Wrist Band',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/usbbracelet.jpg',
category_id: '9',
thumb: 'products/IMG_1442.jpg',
thumbtwo: 'products/IMG_1444.jpg',
thumbthree: 'products/IMG_1449.jpg'
)
# . . .
Product.create!(title: 'Clip USB',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/clip-usb.jpg',
category_id: '9',
thumb: 'products/IMG_1394.jpg',
thumbtwo: 'products/IMG_1541.jpg'
)
# . . .
Product.create!(title: 'Novelty USBs',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/gold.jpg',
category_id: '9',
thumb: 'products/IMG_1415.jpg',
thumbtwo: 'products/IMG_1478.jpg',
thumbthree: 'products/IMG_1410.jpg'
)
# . . .
Product.create!(title: 'USB with Charging Cords',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/IMG_1418.jpg',
category_id: '9',
thumb: 'products/IMG_1419.jpg'
)
# . . .
Product.create!(title: 'USB',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/IMG_1413.jpg',
category_id: '9',
thumb: 'products/IMG_1493.jpg'
)
# . . .
Product.create!(title: 'Wooden USBs',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/IMG_1489.jpg',
category_id: '9',
thumb: 'products/IMG_1488.jpg',
thumbtwo: 'products/IMG_1475.jpg',
thumbthree: 'products/woodusb.png'
)
# . . .
Product.create!(title: 'Eco-Friendly Wine Bags',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/_IMG_052.JPG',
category_id: '3',
thumb: 'products/_MG_3980.jpg',
thumbtwo: 'products/_MG_3982.jpg',
thumbthree: 'products/_MG_3989-2.jpg'
)
# . . .
Product.create!(title: 'Eco-Friendly Shopping Bags',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/_IMG_189.JPG',
category_id: '3',
thumb: 'products/IMG_242.jpg',
thumbtwo: 'products/IMG_247.jpg',
thumbthree: 'products/_MG_4004.jpg'
)
# . . .
Product.create!(title: 'Agra Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/Agra-brown.jpg',
category_id: '3',
thumb: 'products/Agra-fuscia.jpg',
thumbtwo: 'products/Agra-white.jpg',
thumbthree: 'products/Agra-yellow.jpg'
)
# . . .
Product.create!(title: 'Angello Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/angello-fuscia.jpg',
category_id: '2',
thumb: 'products/angello-brown.jpg',
thumbtwo: 'products/angello-limegreen.jpg',
thumbthree: 'products/angello-tango.jpg'
)
# . . .
Product.create!(title: 'Arielle Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/arielle-lime.jpg',
category_id: '2',
thumb: 'products/arielle-brown.jpg',
thumbtwo: 'products/arielle-fuchsia.jpg',
thumbthree: 'products/arielle-tango.jpg'
)
# . . .
Product.create!(title: 'Block Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/block-black.jpg',
category_id: '2',
thumb: 'products/block-blue.jpg',
thumbtwo: 'products/block-natural.jpg',
thumbthree: 'products/block-white.jpg'
)
# . . .
Product.create!(title: 'Bloom Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/bloom-green.jpg',
category_id: '2',
thumb: 'products/bloom-orange.jpg',
thumbtwo: 'products/bloom-purple.jpg',
thumbthree: 'products/bloom-yellow.jpg'
)
# . . .
Product.create!(title: 'Brooklyn Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/brooklyn-blue.jpg',
category_id: '2',
thumb: 'products/brooklyn-fuchsia.jpg',
thumbtwo: 'products/brooklyn-purple.jpg',
thumbthree: 'products/brooklyn-yellow.jpg'
)
# . . .
Product.create!(title: 'Dmask Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/damask-tango.jpg',
category_id: '2',
thumb: 'products/dmask-black.jpg',
thumbtwo: 'products/dmask-blue.jpg',
thumbthree: 'products/dmask-smokegrey.jpg'
)
# . . .
Product.create!(title: 'Emma Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/Emma-beige.jpg',
category_id: '2',
thumb: 'products/Emma-black.jpg',
thumbtwo: 'products/Emma-duskblue.jpg',
thumbthree: 'products/Emma-purple.jpg'
)
# . . .
Product.create!(title: 'Ernie Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/ernie-fuchsia.jpg',
category_id: '2',
thumb: 'products/ernie-lime.jpg',
thumbtwo: 'products/ernie-mauve.jpg',
thumbthree: 'products/ernie-tango.jpg'
)
# . . .
Product.create!(title: 'Fantasia Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/fantasia-aubergine.jpg',
category_id: '2',
thumb: 'products/fantasia-brown.jpg',
thumbtwo: 'products/fantasia-oceanblue.jpg',
thumbthree: 'products/fantasia-yellow.jpg'
)
# . . .
Product.create!(title: 'Fleur Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/fleur-black.jpg',
category_id: '2',
thumb: 'products/fleur-duskblue.jpg',
thumbtwo: 'products/fleur-fushia.jpg',
thumbthree: 'products/fleur-green.jpg'
)
# . . .
Product.create!(title: 'Fringe Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/fringe-aubergine.jpg',
category_id: '2',
thumb: 'products/fringe-blue.jpg',
thumbtwo: 'products/fringe-paprika.jpg',
thumbthree: 'products/fringe-peacock.jpg'
)
# . . .
Product.create!(title: 'Hawaii Surf Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/hawaii.jpg',
category_id: '2'
)
# . . .
Product.create!(title: 'Helena Slouchy Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/helena-black.jpg',
category_id: '2',
thumb: 'products/helena-blue.jpg',
thumbtwo: 'products/helena-brown.jpg',
thumbthree: 'products/helena-red.jpg'
)
# . . .
Product.create!(title: 'Iris Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/iris-canaryyellow.jpg',
category_id: '2',
thumb: 'products/iris-fushia.jpg',
thumbtwo: 'products/iris-purple.jpg',
thumbthree: 'products/iris-tango.jpg'
)
# . . .
Product.create!(title: 'jaipur Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/damask-tango.jpg',
category_id: '2',
thumb: 'products/jaipur-blue.jpg',
thumbtwo: 'products/jaipur-fushia.jpg',
thumbthree: 'products/jaipur-smokegrey.jpg'
)
# . . .
Product.create!(title: 'Jordan Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/jordan-blue.jpg',
category_id: '2',
thumb: 'products/jordan-green.jpg',
thumbtwo: 'products/jordan-orange.jpg',
thumbthree: 'products/jordan-red.jpg'
)
# . . .
Product.create!(title: 'Leafy Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/leafy-brown.jpg',
category_id: '2',
thumb: 'products/leafy-duskblue.jpg',
thumbtwo: 'products/leafy-fushia.jpg',
thumbthree: 'products/leafy-green.jpg'
)
# . . .
Product.create!(title: 'Lorenzo Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/lorenzo-blue.jpg',
category_id: '2',
thumb: 'products/lorenzo-lime.jpg',
thumbtwo: 'products/lorenzo-red.jpg',
thumbthree: 'products/lorenzo-tango.jpg'
)
# . . .
Product.create!(title: 'Lorita Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/Lorita-tango.jpg',
category_id: '2',
thumb: 'products/lorita-fuchsia.jpg',
thumbtwo: 'products/lorita-blue.jpg',
thumbthree: 'products/lorita-lime.jpg'
)
# . . .
Product.create!(title: 'Marina Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/marina-blue.jpg',
category_id: '2',
thumb: 'products/marina-brown.jpg',
thumbtwo: 'products/marina-olive.jpg',
thumbthree: 'products/marina-purple.jpg'
)
# . . .
Product.create!(title: 'Megan Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/megan-blue.jpg',
category_id: '2',
thumb: 'products/megan-fushia.jpg',
thumbtwo: 'products/megan-limegreen.jpg',
thumbthree: 'products/megan-tango.jpg'
)
# . . .
Product.create!(title: 'Melanie Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/melanie-black.jpg',
category_id: '2',
thumb: 'products/melanie-blue.jpg',
thumbtwo: 'products/melanie-fushia.jpg',
thumbthree: 'products/melanie-paprika.jpg'
)
# . . .
Product.create!(title: 'Monet Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/monet-brown.jpg',
category_id: '2',
thumb: 'products/monet-fushia.jpg',
thumbtwo: 'products/monet-green.jpg',
thumbthree: 'products/monet-paprika.jpg'
)
# . . .
Product.create!(title: 'Paisley Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/paisley-black.jpg',
category_id: '2',
thumb: 'products/paisley-blue.jpg',
thumbtwo: 'products/paisley-paprika.jpg',
thumbthree: 'products/paisley-purple.jpg'
)
# . . .
Product.create!(title: 'Piper Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/piper-duskblue.jpg',
category_id: '2',
thumb: 'products/piper-fushia.jpg',
thumbtwo: 'products/piper-peacockblue.jpg',
thumbthree: 'products/piper-yellow.jpg'
)
# . . .
Product.create!(title: 'Pop Art Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/popart-natural.jpg',
category_id: '2',
thumb: 'products/popart-pink.jpg',
thumbtwo: 'products/popart-white.jpg',
thumbthree: 'products/popart-yellow.jpg'
)
# . . .
Product.create!(title: 'Safari Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/safari-blue.jpg',
category_id: '2',
thumb: 'products/safari-orange.jpg',
thumbtwo: 'products/safari-pink.jpg',
thumbthree: 'products/safari-yellow.jpg'
)
# . . .
Product.create!(title: 'Sanchez Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/sanchez-black.jpg',
category_id: '2',
thumb: 'products/sanchez-duskblue.jpg',
thumbtwo: 'products/sanchez-mauve.jpg',
thumbthree: 'products/sanchez-peacockblue.jpg'
)
# . . .
Product.create!(title: 'Sebastin Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/sebastin-black.jpg',
category_id: '2',
thumb: 'products/sebastin-duskblue.jpg',
thumbtwo: 'products/sebastin-fushia.jpg',
thumbthree: 'products/sebastin-peacockblue.jpg'
)
# . . .
Product.create!(title: 'Sheeba Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/sheeba-aubergine.jpg',
category_id: '2',
thumb: 'products/sheeba-blue.jpg',
thumbtwo: 'products/sheeba-lime.jpg',
thumbthree: 'products/sheeba-mauve.jpg'
)
# . . .
Product.create!(title: 'Shilpi Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/shilpi-duskblue.jpg',
category_id: '2',
thumb: 'products/shilpi-grey.jpg',
thumbtwo: 'products/shilpi-peacockblue.jpg',
thumbthree: 'products/shilpi-tblue.jpg'
)
# . . .
Product.create!(title: 'Shimmer Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/shimmer-aubergine.jpg',
category_id: '2',
thumb: 'products/shimmer-black.jpg',
thumbtwo: 'products/shimmer-brown.jpg',
thumbthree: 'products/shimmer-natural.jpg'
)
# . . .
Product.create!(title: 'Snowball Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/snowball-fushia.jpg',
category_id: '2',
thumb: 'products/snowball-paprika.jpg',
thumbtwo: 'products/snowball-purple.jpg',
thumbthree: 'products/snowball-yellow.jpg'
)
# . . .
Product.create!(title: 'Surf Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/surf-blue.jpg',
category_id: '2',
thumb: 'products/surf-lime.jpg',
thumbtwo: 'products/surf-red.jpg',
thumbthree: 'products/surf-yellow.jpg'
)
# . . .
Product.create!(title: 'Sweetheart Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/sweetheart-white.jpg',
category_id: '2',
thumb: 'products/sweetheart-mauve.jpg',
thumbtwo: 'products/sweetheart-natural.jpg',
thumbthree: 'products/sweetheart-yellow.jpg'
)
# . . .
Product.create!(title: 'Tahiti Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/tahiti-peacockblue.jpg',
category_id: '2',
thumb: 'products/tahiti-pink.jpg',
thumbtwo: 'products/tahiti-purple.jpg',
thumbthree: 'products/tahiti-rustred.jpg'
)
# . . .
Product.create!(title: 'Trendy Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/trendy-brown.jpg',
category_id: '2',
thumb: 'products/trendy-duskblue.jpg',
thumbtwo: 'products/trendy-tango.jpg',
thumbthree: 'products/trendy-tblue.jpg'
)
# . . .
Product.create!(title: 'Tulip Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/tulip-fushia.jpg',
category_id: '2',
thumb: 'products/tulip-lilac.jpg',
thumbtwo: 'products/tulip-paprika.jpg',
thumbthree: 'products/tulip-yellow.jpg'
)
# . . .
Product.create!(title: 'Vegas Bag',
description:
%{<p>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p>},
image_url: 'products/vegas-orange.jpg',
category_id: '2',
thumb: 'products/vegas-blue.jpg',
thumbtwo: 'products/vegas-pink.jpg',
thumbthree: 'products/vegas-yellow.jpg'
)
|
class Fase2sController < ApplicationController
before_action :set_fase2, only: [:show, :edit, :update, :destroy]
# GET /fase2s
# GET /fase2s.json
def index
@fase2s = Fase2.all
end
# GET /fase2s/1
# GET /fase2s/1.json
def show
end
# GET /fase2s/new
def new
@fase2 = Fase2.new
end
# GET /fase2s/1/edit
def edit
end
# POST /fase2s
# POST /fase2s.json
def create
@fase2 = Fase2.new(fase2_params)
respond_to do |format|
if @fase2.save
format.html { redirect_to @fase2, notice: 'Segunda fase criada com sucesso' }
format.json { render :show, status: :created, location: @fase2 }
else
format.html { render :new }
format.json { render json: @fase2.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /fase2s/1
# PATCH/PUT /fase2s/1.json
def update
respond_to do |format|
if @fase2.update(fase2_params)
format.html { redirect_to @fase2, notice: 'Segunda fase editada com sucesso' }
format.json { render :show, status: :ok, location: @fase2 }
else
format.html { render :edit }
format.json { render json: @fase2.errors, status: :unprocessable_entity }
end
end
end
# DELETE /fase2s/1
# DELETE /fase2s/1.json
def destroy
@fase2.destroy
respond_to do |format|
format.html { redirect_to fase2s_url, notice: 'Segunda fase apagada com sucesso' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_fase2
@fase2 = Fase2.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def fase2_params
params.require(:fase2).permit(:nome)
end
end
|
class EventManagement::EventsController < EventManagement::ApplicationController
def index
@event_management_events = EventManagement::Event.filter_user_by(@current_user.id)
end
def show
@event_management_event = EventManagement::Event.find(params[:id])
end
def edit
@event_management_event = EventManagement::Event.find(params[:id])
end
def new
end
def update
@event_management_event = EventManagement::Event.find(params[:id])
@event_management_event.update!(event_management_event_params)
redirect_to event_management_events_path(@event_management_event.event), notice: 'イベント情報を更新しました'
end
private
def event_management_event_params
params.require(:event).permit(
:name,
:tag,
:start_at,
:end_at
)
end
end
|
require "geofips/version"
require "csv"
module Geofips
class Location
attr_reader :lat, :lng, :ne_lat, :ne_lng, :sw_lat, :sw_lng
def initialize(code)
@lat = 0.0
@lng = 0.0
@ne_lat = 0.0
@ne_lng = 0.0
@sw_lat = 0.0
@sw_lng = 0.0
location_rows = CSV.read(File.expand_path('../data/locations.csv', __FILE__), { headers: true, header_converters: :symbol })
location_row = find_by_code(location_rows, code)
end
private
def find_by_code(locations, code)
locations.each do |loc|
if loc[:fips] == code
@lat = loc[:lat]
@lng = loc[:lng]
@ne_lat = loc[:ne_lat]
@ne_lng = loc[:ne_lng]
@sw_lat= loc[:sw_lat]
@sw_lng= loc[:sw_lng]
end
end
end
end
end
|
class Field < ActiveRecord::Base
belongs_to :local
has_many :line_items
before_destroy :ensure_not_referenced_by_any_line_item
private
# ensure that there are no line items referencing this product
def ensure_not_referenced_by_any_line_item
if line_items.empty?
return true
else
errors.add(:base, 'no hay Campos Seleccionados')
return false
end
end
###validates_presence_of :descripcion, :local_id
#TURNOS_TYPES = [ "Manana", "Tarde", "Noche" ]
validates :tarifa, :numericality => {:greater_than_or_equal_to => 0.01}
validates :nombre, :caracteristicas, :presence => true
validates :imagen, :format => {
:with => %r{\.(gif|jpg|png)$}i,
:message => 'El formato para las fotos es GIF, JPG or PNG.'
}
#validates :turno, :inclusion => TURNOS_TYPES
end
|
$:.push File.expand_path("../lib", __FILE__)
require "warden/rails/version"
Gem::Specification.new do |s|
s.name = "warden-rails"
s.version = Warden::Rails::VERSION
s.authors = ["Adrià Planas"]
s.email = ["adriaplanas@liquidcodeworks.com"]
s.summary = "Thin wrapper around Warden for Rails 3.2+"
s.files = Dir["lib/**/*"] + ["LICENSE", "Rakefile", "README.md"]
s.test_files = Dir["test/**/*"]
s.add_dependency "railties", ">= 3.2"
s.add_dependency "warden", "~> 1.2.1"
s.add_development_dependency "mocha"
end
|
class ProjectUsersController < ApplicationController
# GET /project_users
# GET /project_users.json
def index
@title = "プロジェクトユーザ一覧"
@catch_phrase = " プロジェクトとユーザの紐付けを行います。"
#@project_users = ProjectUser.all
@project_users = ProjectUser.joins('INNER JOIN projects ON project_users.project_id = projects.id')
.joins('INNER JOIN users ON project_users.user_id = users.id')
.where('projects.delete_flag = false').where('users.available = true')
.order('projects.name ASC').order('users.user_name ASC')
respond_to do |format|
format.html # index.html.erb
format.json { render json: @project_users }
end
end
# GET /project_users/1
# GET /project_users/1.json
def show
@title = "プロジェクトユーザ詳細"
@catch_phrase = "プロジェクトユーザの詳細情報を表示します。"
@project_user = ProjectUser.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @project_user }
end
end
# GET /project_users/new
# GET /project_users/new.json
def new
@project_user = ProjectUser.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @project_user }
end
end
# GET /project_users/1/edit
def edit
@project_user = ProjectUser.find(params[:id])
end
# POST /project_users
# POST /project_users.json
def create
@project_user = ProjectUser.new(params[:project_user])
respond_to do |format|
if @project_user.save
format.html { redirect_to @project_user, notice: '作成が完了しました!' }
format.json { render json: @project_user, status: :created, location: @project_user }
else
format.html { render action: "new" }
format.json { render json: @project_user.errors, status: :unprocessable_entity }
end
end
end
# PUT /project_users/1
# PUT /project_users/1.json
def update
@project_user = ProjectUser.find(params[:id])
respond_to do |format|
if @project_user.update_attributes(params[:project_user])
format.html { redirect_to @project_user, notice: '更新が完了しました!' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @project_user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /project_users/1
# DELETE /project_users/1.json
def destroy
@project_user = ProjectUser.find(params[:id])
@project_user.destroy
respond_to do |format|
format.html { redirect_to project_users_url }
format.json { head :no_content }
end
end
end
|
# == Schema Information
#
# Table name: release_order_envs
#
# id :integer not null, primary key
# release_order_id :integer
# env_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_release_order_envs_on_env_id (env_id)
# index_release_order_envs_on_release_order_id (release_order_id)
#
class ReleaseOrderEnv < ActiveRecord::Base
belongs_to :release_order
belongs_to :env
end
|
require 'sqlite3'
require_relative 'questions_db'
require_relative 'questions'
class QuestionsFollows
def self.all
questions_follows = QuestionsDBConnection.instance.execute("SELECT * FROM questions_follows")
questions_follows.map { |datum| QuestionsFollows.new(datum) }
end
def self.find_by_id(id)
questions_follows = QuestionsDBConnection.instance.execute(<<-SQL, id)
SELECT * FROM questions_follows WHERE id = ?
SQL
end
def self.find_by_question_id(question_id)
questions_follows = QuestionsDBConnection.instance.execute(<<-SQL, question_id)
SELECT * FROM questions_follows WHERE question_id = ?
SQL
end
def self.followers_for_questions(question_id)
questions_follows = QuestionsDBConnection.instance.execute(<<-SQL, question_id)
SELECT
fname, lname
FROM
users
JOIN
questions_follows ON questions_follows.user_id = users.id
WHERE
questions_follows.question_id = ?;
SQL
end
def self.follow_questions_for_user_id(user_id)
questions_follows = QuestionsDBConnection.instance.execute(<<-SQL, user_id)
SELECT
questions.*
FROM
questions
JOIN
questions_follows ON questions_follows.question_id = questions.id
WHERE
questions_follows.user_id = ?;
SQL
questions_follows.map { |datum| QuestionsFollows.new(datum) }
end
def self.most_followed_questions(n)
questions_follows = QuestionsDBConnection.instance.execute(<<-SQL, n )
SELECT DISTINCT
questions.*
FROM
questions
JOIN
questions_follows ON questions_follows.question_id = questions.id
GROUP BY
question_id
ORDER BY
COUNT DESC
LIMIT ?
;
SQL
questions_follows.map { |datum| Questions.new(datum) }
end
def initialize(options)
@id = options['id']
@question_id = options['question_id']
@user_id = options['user_id']
end
end |
class AddAmountToDonations < ActiveRecord::Migration[5.0]
def change
add_column :donations, :amount, :integer, :default => 5
add_column :donations, :user_id, :integer
add_column :donations, :restaurant_id, :integer
end
end
|
# frozen_string_literal: true
module Reports
class Material < Base
def receipts
@receipts ||= Receipt.completed
.where(delivered_at: start_date..end_date)
.where(destination_type: "User")
.where(origin_type: "CollectionPoint")
.includes(destination: [:address], inventory_lines: [:product])
end
def material_delivered
return @material_delivered if defined?(@material_delivered)
@material_delivered = inventory_lines.each_with_object({}) do |line, hsh|
hsh[line.product.name] ||= 0
hsh[line.product.name] += line.quantity_present
end.to_a
end
def recipients
return @recipients if defined?(@recipients)
@precipients = receipts.each_with_object({}) do |receipt, hsh|
user = receipt.destination.to_s
hsh[user] ||= 0
receipt.inventory_lines.each { |il| hsh[user] += il.quantity_present }
end.to_a
end
def collection_points
return @collection_points if defined?(@collection_points)
@collection_points = receipts.each_with_object({}) do |receipt, hsh|
cp = receipt.origin.to_s
hsh[cp] ||= 0
receipt.inventory_lines.each { |il| hsh[cp] += il.quantity_present }
end.to_a
end
def receipt_count
@receipts.count
end
def to_h
{
material_delivered: material_delivered,
recipients: recipients,
collection_points: collection_points,
receipt_count: receipt_count,
start_date: start_date.to_date,
end_date: end_date.to_date
}
end
private
def inventory_lines
@inventory_lines = receipts&.map(&:inventory_lines)&.flatten || []
end
end
end
|
require 'spec_helper'
require_relative '../lib/grid_partition/node.rb'
describe GridPartition::Node do
context "::initialize" do
it 'should give a instance w/ 3 argument' do
node = GridPartition::Node.new(1,2,1.0)
node.should_not be_nil
end
it 'should not accept minus value argument' do
expect{
GridPartition::Node.new(-1,1.0,1.0)
}.to raise_error(ArgumentError)
end
it "should accept only [integer,integer] for @x, @y" do
expect{
GridPartition::Node.new(1,1.0,1.0)
}.to raise_error(ArgumentError)
expect{
GridPartition::Node.new(1.0,1.0,1.0)
}.to raise_error(ArgumentError)
expect{
GridPartition::Node.new(1,1.0,1.0)
}.to raise_error(ArgumentError)
end
it 'should not give an instance w/o argument' do
expect{
GridPartition::Node.new()
}.to raise_error(ArgumentError)
end
end
end
|
require 'csv'
class Exporter
attr_reader :scope
def self.run
self.new.run
end
def initialize(scope = nil)
@scope = scope
end
def run
data = message_data
CSV.open("public/#{path}", 'w') do |csv|
csv << MessageCSVPresenter::HEADERS
data.each do |row|
csv << row
end
end
path
end
def message_data
scope ? Message.send(scope).map(&:to_row) : Message.all.map(&:to_row)
end
private
def filename
scope ? "#{scope.to_s}_messages.csv" : "messages.csv"
end
def path
"export/#{filename}"
end
end
|
require_relative 'patient'
class Room
attr_reader :patients, :door_number
attr_accessor :id
def initialize(attributes = {})
@id = attributes[:id]
@door_number = attributes[:door_number]
@number_of_beds = attributes[:number_of_beds] || 0
@patients = attributes[:patients] || []
end
def full?
@patients.size == @number_of_beds
end
def add_patient(patient)
# self => is the room on which .add_patient was called
if full?
raise Exception
else
@patients << patient
patient.room = self
end
end
end
rock_room = Room.new(
door_number: "Rock 01",
number_of_beds: 2
)
ozzy = Patient.new(
name: "Ozzy Osbourne",
illness: "Dementia"
)
andre = Patient.new(
name: "Marcos André",
cured: true
)
eduardo = Patient.new
rock_room.add_patient(ozzy)
rock_room.add_patient(andre)
# puts ozzy.room.door_number |
Vagrant.configure("2") do |config|
config.vm.provider :virtualbox do |vb|
vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
vb.customize ["modifyvm", :id, "--natdnsproxy1", "on"]
end
config.vm.define "cust1-core" do |server|
server.vm.box = "generic/ubuntu2004"
server.vm.hostname = "cust1-core"
# Copy bird config config
server.vm.provision "file", source: "cust1-core.bird.conf", destination: "/tmp/bird.conf"
# Copy bashrd aliases
server.vm.provision "file", source: "bashrc", destination: "/tmp/bashrc"
# cust1-core1<->cust1-ce1
server.vm.network "private_network", ip: "192.168.12.12", netmask: "255.255.255.0"
# cust1-core1<->cust1-ce2
server.vm.network "private_network", ip: "192.168.13.12", netmask: "255.255.255.0"
# for inside world
server.vm.network "private_network", ip: "192.168.11.11", netmask: "255.255.255.0"
# do basic setup
server.vm.provision "shell", privileged: true, path: "basic-setup.sh"
end
config.vm.define "cust1-ce1" do |server|
server.vm.box = "generic/ubuntu2004"
server.vm.hostname = "cust1-ce1"
# Copy bird config config
server.vm.provision "file", source: "cust1-ce1.bird.conf", destination: "/tmp/bird.conf"
# Copy bashrd aliases
server.vm.provision "file", source: "bashrc", destination: "/tmp/bashrc"
# cust1-ce1<->cust1-core1
server.vm.network "private_network", ip: "192.168.12.11", netmask: "255.255.255.0"
# cust1-ce1<->cust1-ce2
server.vm.network "private_network", ip: "192.168.14.11", netmask: "255.255.255.0"
# cust1-ce1<->sp1-p1
server.vm.network "private_network", ip: "10.10.1.12", netmask: "255.255.255.0"
# do basic setup
server.vm.provision "shell", privileged: true, path: "basic-setup.sh"
end
config.vm.define "cust1-ce2" do |server|
server.vm.box = "generic/ubuntu2004"
server.vm.hostname = "cust1-ce2"
# Copy bird config config
server.vm.provision "file", source: "cust1-ce2.bird.conf", destination: "/tmp/bird.conf"
# Copy bashrd aliases
server.vm.provision "file", source: "bashrc", destination: "/tmp/bashrc"
# cust1-ce2<->cust1-core1
server.vm.network "private_network", ip: "192.168.13.11", netmask: "255.255.255.0"
# cust1-ce1<->cust1-ce2
server.vm.network "private_network", ip: "192.168.14.12", netmask: "255.255.255.0"
# cust1-ce2<->sp2-p1
server.vm.network "private_network", ip: "10.11.1.12", netmask: "255.255.255.0"
# do basic setup
server.vm.provision "shell", privileged: true, path: "basic-setup.sh"
end
config.vm.define "sp1-p1" do |server|
server.vm.box = "generic/ubuntu2004"
server.vm.hostname = "sp1-p1"
# Copy bird config config
server.vm.provision "file", source: "sp1-p1.bird.conf", destination: "/tmp/bird.conf"
# Copy bashrd aliases
server.vm.provision "file", source: "bashrc", destination: "/tmp/bashrc"
# sp1-p1<->cust1-ce1
server.vm.network "private_network", ip: "10.10.1.11", netmask: "255.255.255.0"
# sp1-p1<->cloud1-ce1
server.vm.network "private_network", ip: "10.10.2.11", netmask: "255.255.255.0"
# do basic setup
server.vm.provision "shell", privileged: true, path: "basic-setup.sh"
end
config.vm.define "sp2-p1" do |server|
server.vm.box = "generic/ubuntu2004"
server.vm.hostname = "sp2-p1"
# Copy bird config config
server.vm.provision "file", source: "sp2-p1.bird.conf", destination: "/tmp/bird.conf"
# Copy bashrd aliases
server.vm.provision "file", source: "bashrc", destination: "/tmp/bashrc"
# sp2-p1<->cust1-ce2
server.vm.network "private_network", ip: "10.11.1.11", netmask: "255.255.255.0"
# sp2-p1<->cloud1-ce1
server.vm.network "private_network", ip: "10.11.2.11", netmask: "255.255.255.0"
# do basic setup
server.vm.provision "shell", privileged: true, path: "basic-setup.sh"
end
config.vm.define "cloud1-ce1" do |server|
server.vm.box = "generic/ubuntu2004"
server.vm.hostname = "cloud1-ce1"
# Copy bird config config
server.vm.provision "file", source: "cloud1-ce1.bird.conf", destination: "/tmp/bird.conf"
# Copy bashrd aliases
server.vm.provision "file", source: "bashrc", destination: "/tmp/bashrc"
# sp1-p1<->cloud1-ce1
server.vm.network "private_network", ip: "10.10.2.12", netmask: "255.255.255.0"
# sp2-p1<->cloud1-ce1
server.vm.network "private_network", ip: "10.11.2.12", netmask: "255.255.255.0"
# for inside world
server.vm.network "private_network", ip: "172.16.100.11", netmask: "255.255.255.0"
# do basic setup
server.vm.provision "shell", privileged: true, path: "basic-setup.sh"
end
end
|
class Score < ActiveRecord::Base
validates_presence_of :option
validates_presence_of :comment
end
|
# frozen_string_literal: true
AUTHORIZED_BIB_TAGS = %w[100 110 111 600 610 611 630 650 651 700 710].freeze
require_relative '../../../../app/models/wikidata_connection'
module FindIt
module Macros
# Checks Wikidata for additional keywords to index
module WikidataEnrichment
def keywords_from_wikidata
proc do |record, accumulator|
uris_from_bib_record = []
record.find_all { |f| AUTHORIZED_BIB_TAGS.include? f.tag }.each do |field|
uris_from_bib_record.concat(field.find_all { |subfield| subfield.code == '9' }.map(&:to_s))
end
accumulator.concat(keywords_for_uris(uris_from_bib_record))
end
end
def keywords_for_uris(uris)
identifier_string = stringify_identifiers(uris_to_identifiers(uris))
wikidata_results identifier_string
end
def wikidata_results(identifier_string)
client = WikidataConnection.new
query = compile_query identifier_string
results = client.query(query)
results.map { |keyword| keyword[:keywordLabel].to_s }
end
def compile_query(identifier_string)
<<~ENDQUERY
SELECT DISTINCT ?keywordLabel
WHERE#{' '}
{
VALUES ?authorities { #{identifier_string} }
?nameProperties wdt:P1647* wd:P2561.
?nameProperties wikibase:directClaim ?nameClaim .
?item wdt:P244 ?authorities.
{?item#{' '}
(wdt:P17|wdt:P101|wdt:P112|wdt:P135|wdt:P136|wdt:P279|wdt:P361|wdt:P460|wdt:P793|wdt:P800|wdt:P1269|wdt:P1344|wdt:P1830|p:P2572/ps:P2572|wdt:P3342|wdt:P3602|wdt:P5004) ?keyword.}
UNION#{' '}
{?item ?nameClaim ?keyword}
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en,es". }
}
ENDQUERY
end
def stringify_identifiers(identifiers)
identifiers.map { |identifier| "\"#{identifier}\"" }
.join(' ')
end
def uris_to_identifiers(uris)
uris.map { |uri| lc_identifier(uri) }
.compact
.uniq
end
# returns the identifier if it is a valid LoC URI; returns nil otherwise
def lc_identifier(uri)
uri.match(%r{http://id\.loc\.gov/authorities/[a-z]*/([a-z0-9]*)})&.captures&.first
end
end
end
end
|
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :identification_type
t.string :identification_number
t.boolean :extra_plates
t.string :plate
t.timestamps
end
end
end |
# To change this template, choose Tools | Templates
# and open the template in the editor.
require 'rubygems'
require 'sqlite3'
require 'inifile'
module Bnicovideo
class UserSession
# Windows 95 and NT 4.x
module Win95
def self.init_from_firefox
# Single user only
base_path = File.join(ENV['windir'], 'Application Data', 'Mozilla', 'Firefox')
ini_path = File.join(base_path, 'profiles.ini')
ini_hash = IniFile.load(ini_path).to_h
profile_path = nil
ini_hash.each do |k, v|
next unless v['Name'] == 'default'
relative = (v['IsRelative'] != '0')
input_path = v['Path']
if relative
profile_path = File.join(base_path, input_path)
else
profile_path = input_path
end
sql_path = File.join(profile_path, 'cookies.sqlite')
conn = SQLite3::Database.new(sql_path)
val = conn.get_first_value("select value from moz_cookies" +
" where host='.nicovideo.jp' AND name='user_session'")
return val
end
return nil
end
def self.init_from_ie
cookies_path = File.join(ENV['windir'], 'Cookie')
Dir.open(cookies_path) do |dir|
dir.each do |fn|
next unless (/.*@nicovideo.*/ =~ fn)
File.open(fn) do |f|
cb = f.read
cs = cb.split(/\*\n/)
cs.each do |c|
ca = c.split(/\n/)
return ca[1] if ca[0] == 'user_session'
end
end
end
end
return nil
end
end
end
end
|
#!/usr/bin/ruby
#
# Red Hat rotates wtmp monthly by default, which causes the loss of
# login history unnecessarily, as most servers are logged into very
# infrequently and wtmp grows very slowly. So we change the rotation to
# be based on the size of wtmp, which results in retention of 1-2 years
# of login history in most cases.
#
in_wtmp_stanza = false
IO.foreach(@original_file) do |line|
if line =~ %r|^\s*/var/log/wtmp|
in_wtmp_stanza = true
elsif line =~ %r|^\s*}|
in_wtmp_stanza = false
elsif in_wtmp_stanza && line =~ %r|^\s*monthly|
# Comment out the monthly setting
line.insert(0, '#')
# And insert a size setting
line << " size 100k\n"
end
@contents << line
end
|
RSpec.describe Api::V1::MoviesController, type: :controller do
describe 'GET index' do
before(:each) do
5.times { create(:movie) }
get :index, format: :json
end
include_examples "check response", "application/json"
it "assigns movies as @movies" do
expect(assigns(:movies)).to match_array(Movie.all)
end
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
# Define layout depending on the called controller
layout :resolve_layout
after_filter :set_csrf_cookie_for_ng
def set_csrf_cookie_for_ng
cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
end
protected
def verified_request?
super || form_authenticity_token == request.headers['X-XSRF-TOKEN']
end
private
def resolve_layout
if user_signed_in?
'private_application'
else
'public_application'
end
end
end
|
class CryptServices
secret_key_credit_cards = Rails.application.credentials[:secret_key_credit_cards]
key = ActiveSupport::KeyGenerator.new('password').generate_key(secret_key_credit_cards, 32)
@crypt = ActiveSupport::MessageEncryptor.new(key)
class << self
def encrypt(data)
@crypt.encrypt_and_sign(data)
end
def decrypt(data)
@crypt.decrypt_and_verify(data)
rescue StandardError => e
:key_invalidate
end
end
end
|
# encoding: UTF-8
class Film
class Personnages
# Path du fichier contenant les données marshalisées
def marshal_file
@marshal_file ||= File.join(film.collecte.data_folder, 'personnages.msh')
end
end #/Personnages
end #/Film
|
require 'spec_helper'
describe User do
it { should have_many(:posts) }
describe '#display_name' do
it 'returns the name of the user if it is available' do
user = build(:user, name: 'Some Name', email: 'user@example.com')
expect(user.display_name).to eq(user.name)
end
it 'returns the email of the user if the name is not available' do
user = build(:user, name: nil, email: 'user@example.com')
expect(user.display_name).to eq(user.email)
end
end
end
|
# Creates sets of different sizes
class SetCreator
# Returns a hash of doubleton ItemSets from singleton ItemSets
def self.create_doubletons(singletons)
item_ids = singletons.map(&:id)
create_doubletons_from_item_ids(item_ids)
end
# Creates permutations of possible frequent item sets
# given item_sets of any size and frequent singletons
def self.create_permutations(item_sets, singletons)
item_ids = singletons.map(&:id)
permutation_ids = item_sets.map(&:all_item_ids)
create_permutations_from_item_ids(item_ids, permutation_ids)
end
private
# Creates a hash with item_id as key and an
# array of doubleton ItemSets as value
def self.create_doubletons_from_item_ids(item_ids)
set_hash = []
item_ids.each_with_index do |item_id, index|
set_hash[item_id] = create_doubletons_array(
item_id,
item_ids[index + 1 .. -1]
)
end
set_hash
end
# Creates tripleton hash from doubletons and singletons
def self.create_permutations_from_item_ids(item_ids, item_sets)
set_hash = []
item_ids.each do |item_id|
set_hash[item_id] = create_permutations_array(
set_hash,
item_id,
item_sets
)
end
set_hash
end
# Creates an array of permutations of all non-duplicate item sets
def self.create_permutations_array(set_hash, item_id, item_sets)
permutations = []
item_sets.each do |item_set|
item_ids = [item_id] + item_set
unless item_set.include?(item_id) || item_set_exists?(set_hash, item_ids)
permutations << ItemSet.new(item_ids)
end
end
permutations
end
# Returns true if this item set already exists
def self.item_set_exists?(set_hash, item_ids)
smallest_id = item_ids.min
row = set_hash[smallest_id]
item_ids = item_ids.sort
if row
row.any? do |item_set|
item_set.include_ids?(item_ids)
end
else
false
end
end
# Creates an array of doubleton ItemSets
def self.create_doubletons_array(item_id, sub_indices)
sub_indices.map do |sub_index|
ItemSet.new([item_id, sub_index])
end
end
end
|
#
# Author:: Jamie Winsor (<jamie@vialstudios.com>)
# Copyright:: 2011, En Masse Entertainment, Inc
# License:: Apache License, Version 2.0
#
# 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 'rubygems'
#require 'bundler'
#Bundler.setup(:default, :test)
require 'spork'
Spork.prefork do
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'dragonfly-ffmpeg'
require 'support/video_matchers'
SAMPLES_DIR = File.expand_path(File.dirname(__FILE__) + '/../samples') unless defined?(SAMPLES_DIR)
require 'logger'
LOG_FILE = File.dirname(__FILE__) + '/spec.log' unless defined?(LOG_FILE)
TMP_DIR = File.dirname(__FILE__) + '/tmp' unless defined?(TMP_DIR)
FileUtils.mkdir_p(TMP_DIR)
FileUtils.rm_rf Dir.glob(TMP_DIR + '/*')
FileUtils.rm_rf(LOG_FILE)
logger = Logger.new(LOG_FILE)
logger.level = Logger::INFO
FFMPEG.logger = logger
def test_app
Dragonfly::App.send(:new)
end
end
Spork.each_run do
# code for each spork run
end
|
RSpec::Support.require_rspec_mocks 'verifying_proxy'
module RSpec
module Mocks
# @private
module VerifyingDouble
def respond_to?(message, include_private=false)
return super unless null_object?
method_ref = __mock_proxy.method_reference[message]
case method_ref.visibility
when :public then true
when :private then include_private
when :protected then include_private || RUBY_VERSION.to_f < 2.0
else !method_ref.unimplemented?
end
end
def method_missing(message, *args, &block)
# Null object conditional is an optimization. If not a null object,
# validity of method expectations will have been checked at definition
# time.
if null_object?
if @__sending_message == message
__mock_proxy.ensure_implemented(message)
else
__mock_proxy.ensure_publicly_implemented(message, self)
end
__mock_proxy.validate_arguments!(message, args)
end
super
end
# Redefining `__send__` causes ruby to issue a warning.
old, $VERBOSE = $VERBOSE, nil
def __send__(name, *args, &block)
@__sending_message = name
super
ensure
@__sending_message = nil
end
ruby2_keywords :__send__ if respond_to?(:ruby2_keywords, true)
$VERBOSE = old
def send(name, *args, &block)
__send__(name, *args, &block)
end
ruby2_keywords :send if respond_to?(:ruby2_keywords, true)
def initialize(doubled_module, *args)
@doubled_module = doubled_module
possible_name = args.first
name = if String === possible_name || Symbol === possible_name
args.shift
end
super(name, *args)
@__sending_message = nil
end
end
# A mock providing a custom proxy that can verify the validity of any
# method stubs or expectations against the public instance methods of the
# given class.
#
# @private
class InstanceVerifyingDouble
include TestDouble
include VerifyingDouble
def __build_mock_proxy(order_group)
VerifyingProxy.new(self, order_group,
@doubled_module,
InstanceMethodReference
)
end
end
# An awkward module necessary because we cannot otherwise have
# ClassVerifyingDouble inherit from Module and still share these methods.
#
# @private
module ObjectVerifyingDoubleMethods
include TestDouble
include VerifyingDouble
def as_stubbed_const(options={})
ConstantMutator.stub(@doubled_module.const_to_replace, self, options)
self
end
private
def __build_mock_proxy(order_group)
VerifyingProxy.new(self, order_group,
@doubled_module,
ObjectMethodReference
)
end
end
# Similar to an InstanceVerifyingDouble, except that it verifies against
# public methods of the given object.
#
# @private
class ObjectVerifyingDouble
include ObjectVerifyingDoubleMethods
end
# Effectively the same as an ObjectVerifyingDouble (since a class is a type
# of object), except with Module in the inheritance chain so that
# transferring nested constants to work.
#
# @private
class ClassVerifyingDouble < Module
include ObjectVerifyingDoubleMethods
end
end
end
|
require 'fileutils'
module OHOLFamilyTrees
class FilesystemLocal
attr_reader :output_dir
def initialize(output_dir)
@output_dir = output_dir
end
def with_metadata(metadata)
self
end
def write(path, metadata = {}, &block)
filepath = "#{output_dir}/#{path}"
FileUtils.mkdir_p(File.dirname(filepath))
File.open(filepath, 'wb', &block)
end
def read(path, &block)
filepath = "#{output_dir}/#{path}"
if File.exist?(filepath)
File.open(filepath, 'rb', &block)
return true
end
end
def open(path)
filepath = "#{output_dir}/#{path}"
if File.exist?(filepath)
return File.open(filepath, 'rb')
end
end
def delete(path)
filepath = "#{output_dir}/#{path}"
if File.exist?(filepath)
File.delete(filepath)
return true
end
end
def list(path)
filepath = "#{output_dir}/#{path}"
notprefix = ("#{output_dir}/".length)..-1
if Dir.exist?(filepath)
return Dir.glob(filepath + "/**/*").map { |entry|
entry[notprefix]
}
end
return []
end
end
end
|
require 'semantic_logger'
module GhBbAudit
module Bitbucket
class BitbucketRepo
include SemanticLogger::Loggable
def initialize(user_name,repo_name)
@user_name = user_name
@repo_name = repo_name
end
def get_all_file_paths
return [] if ( !@user_name || !@repo_name )
begin
bb_client = ::BitBucket.new {|config| config.endpoint = 'https://bitbucket.org/api/1.0'}
@paths ||= get_files_in_dir('',bb_client)
rescue StandardError => e
logger.error "BITBUCKET:: Error in geting files for Bitbucket Repo:: #{@repo_name} for User:: #{@user_name}", error: e.inspect
end
@paths
end
private
def get_files_in_dir(path,bb_client)
bb_response = bb_client.repos.sources.get @user_name, @repo_name, 'master', path
files = bb_response["files"].collect(&:path) rescue []
files_in_directory = begin
bb_response["directories"].each.inject([]) do |result,dir_name|
result << get_files_in_dir(path + '/' + dir_name, bb_client)
end
rescue StandardError => e
logger.error "BITBUCKET:: Error in geting files for Bitbucket Repo:: #{@repo_name} for User:: #{@user_name} and path:: #{path}", error: e.inspect
[]
end
return (files + files_in_directory).flatten
end
end
end
end |
class Board
attr_accessor :state
def initialize(state=nil)
@state = (state || Array.new(9))
end
def valid_step?(step)
self[step].nil?
end
def get_available_steps
@state.each.with_index(1).select { |mark, index| mark.nil? }.map { |mark, index| index }
end
def new_board(step, mark)
board = self.class.new @state.dup
board[step] = mark
board
end
def [](step)
raise IndexError, "Bad step: #{step}" unless step.between?(1, 9)
@state[step - 1]
end
def []=(step, mark)
raise ArgumentError, "step already taken: #{step}" unless valid_step? step
@state[step - 1] = mark
end
def full?
!@state.include?(nil)
end
def display
puts
@state.each.with_index do |value, pos|
value ||= (pos + 1)
if pos % 3 == 1
print "| #{value} |"
else
print " #{value} "
end
puts "\n---+---+---" if [2, 5].include? pos
end
puts
end
end
|
class AddDefault0ToSearches < ActiveRecord::Migration
def change
change_column :talent_domains, :times_searched, :integer, :default =>0
change_column :talent_domains, :times_used, :integer, :default =>0
change_column :keywords, :times_searched, :integer, :default =>0
change_column :keywords, :times_used, :integer, :default =>0
end
end
|
FactoryBot.define do
factory :document do
country { ISO3166::Country.all_translated('EN').sample }
document_type { Document.document_types.keys.sample }
issued_at { 5.years.ago }
expired_at { 5.years.from_now }
number { 123 }
end
end
|
class CustomersController < ApplicationController
before_action :authenticate_customer!
before_action :set_customer,only: [:edit,:show,:withdraw]
def show
set_customer
if @customer != current_customer
redirect_to items_path
end
end
def edit
set_customer
if @customer != current_customer
redirect_to items_path
end
end
def update
@customer = Customer.find(params[:id])
if @customer.update(customer_params)
redirect_to customer_path(@customer)
else
render 'edit'
end
end
def withdraw
set_customer
if @customer != current_customer
redirect_to items_path
end
end
def status_change
customer = Customer.find(params[:id])
sign_out(Customer)
customer.update(change_params)
redirect_to root_path
end
def set_customer
@customer = Customer.find_by(id: params[:id])
end
private
def customer_params
params.require(:customer).permit(:last_name, :first_name, :last_name_kana, :first_name_kana, :postal_code, :address, :phone_number, :email, :customer_status)
end
def change_params
params.permit(:customer_status)
end
end
|
class DashboardBaseGenerator < Rails::Generators::Base
source_root File.expand_path('templates', __dir__)
def create_dashboard_base_controller
copy_file "dashboard_base_controller.rb", "app/controllers/dashboard_base_controller.rb"
end
def create_dashboard_base_file
copy_file "dashboard_base.rb", "app/views/layouts/dashboard_base.html.slim"
end
def create_sidebar_base_file
copy_file "sidebar.rb", "app/views/layouts/_sidebar.html.slim"
end
def create_dashboard_contoller
copy_file "dashboard_controller.rb", "app/controllers/dashboards_controller.rb"
end
def create_dashboard_index
copy_file "dashboard_index.html.rb", "app/views/dashboards/index.html.slim"
end
def create_login_page
copy_file "login.rb", "app/views/devise/sessions/new.html.slim"
end
def create_registration_page
copy_file "registration.rb", "app/views/devise/registrations/new.html.slim"
end
def create_application_slim
copy_file "application_slim.rb", "app/views/layouts/application.html.slim"
end
def upload_avatar_pic
copy_file "avatar.png", "app/assets/images/avatar.png"
end
end |
#!/usr/bin/env ruby
num = (1..999)
def multiple(num)
num.select do |x|
x %3 == 0 || x %5 == 0
end
end
puts multiple(num).reduce(:+)
|
class GenresController < ApplicationController
def new
@genre = Genre.new
end
def update
# @post = Post.find(params[:id])
# @schoolclass = SchoolClass.find(params[:id])
# @student = Student.find(params[:id])
# @artist = Artist.find(params[:id])
@genre = Genre.find(params[:id])
# @post.update(title: params[:title], description: params[:description])
@genre.update(genre_params(:name))
#
# redirect_to post_path(@post)
redirect_to genre_path(@genre)
end
def show
@genre = Genre.find(params[:id])
end
def edit
@genre = Genre.find(params[:id])
end
def create
@genre = Genre.new(genre_params(:name))
@genre.save
redirect_to genre_path(@genre)
end
def genre_params(*args)
params.require(:genre).permit(*args)
end
end
|
require 'rails_helper'
describe 'sweater weather api' do
before(:each) do
@user = User.create(email: 'foofoo@gmail.com', password: 'password', password_confirmation: 'password')
end
it 'can login a registered user with valid credentials' do
post "/api/v1/sessions", :params => '{ "email": "foofoo@gmail.com", "password": "password" }', :headers => { "CONTENT_TYPE" => "application/json" }
expect(response).to be_successful
expect(response.status).to eq(200)
expect( JSON.parse(response.body)['data']['attributes']['api_key']).to eq(@user.api_key)
end
it 'returns a 400 status for unsuccessful requests with a description' do
post "/api/v1/sessions", :params => '{ "email": "foofoo@gmail.com" }', :headers => { "CONTENT_TYPE" => "application/json" }
expect(response.status).to eq(400)
expect(JSON.parse(response.body)['data']['attributes']['message']).to eq('Please enter valid credentials')
end
it 'returns a 400 status and message if account not found' do
post "/api/v1/sessions", :params => '{ "email": "barbar@gmail.com", "password": "password" }', :headers => { "CONTENT_TYPE" => "application/json" }
expect(response.status).to eq(400)
expect(JSON.parse(response.body)['data']['attributes']['message']).to eq('No account found')
end
end
|
require 'fdk'
def myfunction(context:, input:)
input_value = input.respond_to?(:fetch) ? input.fetch('name') : input
name = input_value.to_s.strip.empty? ? 'World' : input_value
{ message: "Hello #{name}!" }
end
FDK.handle(target: :myfunction)
|
require_relative '../test_helper'
class PayloadTest < TrafficTest
include PayloadPrep
def setup
setup_model_testing_environment
@user = TrafficSpy::User.find(1)
@user_url_blog = @user.payloads.where(url: "http://jumpstartlab.com/blog")
end
def test_url_popularity
expected_result = {"http://jumpstartlab.com/blog"=>2, "http://jumpstartlab.com/weather"=>1}
assert_equal expected_result, @user.payloads.url_popularity
end
def test_browser_popularity
expected_result = {"Chrome"=>2, "Safari"=>1}
assert_equal expected_result, @user.payloads.browser_popularity
end
def test_os_popularity
expected_result = {"Macintosh"=>2, "Windows"=>1}
assert_equal expected_result, @user.payloads.os_popularity
end
def test_resolution_popularity
expected_result = {1=>2, 2=>1}
assert_equal expected_result, @user.payloads.resolution_popularity
end
def test_avg_response_time
actual_result = @user.payloads.avg_response_time.map { |k, v| v}
assert_equal [38, 39], actual_result
end
def test_max_response_time
actual_result = @user_url_blog.max_response_time
assert_equal 39, actual_result
end
def test_min_response_time
actual_result = @user_url_blog.min_response_time
assert_equal 37, actual_result
end
def test_avg_response_time_per_url
actual_result = @user_url_blog.average_response_time_per_url
assert_equal 38, actual_result
end
def test_http_verbs
actual_result = @user_url_blog.http_verbs
assert_equal ["GET", "POST"], actual_result
end
def test_most_popular_referrers
actual_result = @user_url_blog.referrers
assert_equal [["http://jumpstartlab.com", 2]], actual_result
end
def test_most_popular_browsers
actual_result = @user_url_blog.browsers
assert_equal [["Chrome", 2]], actual_result
end
def test_known_url?
actual_result = @user.payloads.known_url?("http://jumpstartlab.com/blog")
assert actual_result
actual_result = @user.payloads.known_url?("http://jumpstartlab.com/pizza")
refute actual_result
end
def test_event_frequency
expected_result = {"socialLogin"=>3}
actual_result = @user.payloads.event_frequency
assert_equal expected_result, actual_result
end
def test_events_by_hour
expected_result = {["socialLogin", 21.0]=>2, ["socialLogin", 19.0]=>1}
actual_result = @user.payloads.events_by_hour('socialLogin')
assert_equal expected_result, actual_result
end
def test_total_events
expected_result = 3
actual_result = @user.payloads.total_events('socialLogin')
assert_equal expected_result, actual_result
end
end
|
module MatchEvent
class Base < ActiveRecord::Base
self.table_name = "match_events"
belongs_to :match
belongs_to :team
belongs_to :player1, class_name: "Player", foreign_key: "player1_id"
belongs_to :player2, class_name: "Player", foreign_key: "player2_id"
scope :for_scoring, -> (player_id) { where(type: MatchEvent::Goal.name, player1_id: player_id) }
def self.create_all_from_match_data(match_data)
# TODO: refactor to loop that uses self.subclasses, but remember that in dev the subclasses are lazy loaded so it shows empty...
match_events = []
match_events += MatchEvent::Goal.create_from_match_data(match_data.with_indifferent_access)
match_events += MatchEvent::YellowCard.create_from_match_data(match_data.with_indifferent_access)
match_events += MatchEvent::RedCard.create_from_match_data(match_data.with_indifferent_access)
match_events += MatchEvent::Substitution.create_from_match_data(match_data.with_indifferent_access)
match_events
end
def self.create_from_match_data(match_data)
bad = []
match_events = []
[:home, :away].each do |side|
data_string = match_data["#{side}_#{match_data_hash_key}"]
return match_events if data_string.blank?
team_id = match_data["#{side}_team_id"]
events = data_string.split(';').reverse
events.each do |event_str|
begin
minute = event_str.match(/(\d+)/).to_a.first
player_name = event_str.match(/[A-Z].+$/).to_a.first.to_s.strip
player = Player.find_by_or_fetch_for_team({ name: player_name }, team_id)
event = self.find_or_initialize_by(match_id: match_data[:id], minute: minute, team_id: match_data["#{side}_team_id"])
event.player1_id = player.try(:id)
event.add_info_from_match_data(match_data, event_str, side)
event.save!
match_events << event
puts "created match event #{self.name} - #{event_str}"
rescue => e
byebug
end
end
end
match_events
end
def add_info_from_match_data(match_data, current_event_string, side)
end
end
end |
#============================================================================
# Unit Circle
#----------------------------------------------------------------------------
# Display under the battler position
#============================================================================
class Unit_Circle < Sprite_Base
#----------------------------------------------------------------------------
attr_accessor :character
#----------------------------------------------------------------------------
# *) Object initialization
#----------------------------------------------------------------------------
def initialize(viewport, character)
super(viewport)
@character = character
self.z = viewport.z
set_bitmap
hide
end
#----------------------------------------------------------------------------
# *) Sets the bitmap
#----------------------------------------------------------------------------
def set_bitmap
self.bitmap = Bitmap.new(32, 32)
if @character.is_a?(Game_Event) && (@character && @character.team_id != 0)
color = DND::COLOR::Red
#draw_sight
else
color = DND::COLOR::Blue
end
self.bitmap.draw_circle( 16, 16, 13, color, 2)
update_position
end
#----------------------------------------------------------------------------
# * Position update
#----------------------------------------------------------------------------
def update_position
return hide if !BattleManager.valid_battler?(@character)
self.x = @character.screen_x - 16
self.y = @character.screen_y - 28
end
#----------------------------------------------------------------------------
# *) Dispose method
#----------------------------------------------------------------------------
def dispose
if self.bitmap != nil && !self.bitmap.disposed?
self.bitmap.dispose
self.bitmap = nil
end
super
end
#----------------------------------------------------------------------------
def show
update_position
self.visible = true
end
#----------------------------------------------------------------------------
def hide
self.visible = false
end
#----------------------------------------------------------------------------
# *) Update Process
#----------------------------------------------------------------------------
def update
return unless self.visible?
self.hide if dead?
update_position
super
end
#----------------------------------------------------------------------------
# Get direction angle
#----------------------------------------------------------------------------
def direction_angle(battler)
d = battler.direction
case d
when 2; return [90,180]
when 4; return [150, 30]
when 6; return [330,210]
when 8; return [300, 60]
end
end
#----------------------------------------------------------------------------
# * Draw sight limit, useless for now
#----------------------------------------------------------------------------
def draw_sight
#return if @character.sensor.nil?
#self.bitmap = load_bitmap("Graphics/Lights/", "RS5")
end
#----------------------------------------------------------------------------
def dead?
return true if @character.is_a?(Game_Event) && @character.enemy.nil?
return @character.dead?
end
#----------------------------------------------------------------------------
def alive?
return !dead?
end
#----------------------------------------------------------------------------
def adjacent?(sx, sy)
return (sx - self.x).abs <= 4 && (sy - self.y).abs <= 4
end
#----------------------------------------------------------------------------
end
|
Types::PdvType = GraphQL::ObjectType.define do
name 'Pdv'
field :id, !types.ID
field :tradingName, !types.String
field :ownerName, !types.String
field :document, !types.String
field :coverageArea, !types.String
field :address, !types.String
end
|
class CommissionCalculator
INSURANCE_PRICE = 100 # in cents
def self.for(rental)
new(rental)
end
def initialize(rental)
@rental = rental
end
# forcing integers to match up with docs, not sure if these things are
# calcuated in cents which is probably why they are all integers
def insurance_fee
(commission / 2.0).to_i
end
def assistance_fee
# a bit pointless for now but if it changes its easy to update
(rental_length * INSURANCE_PRICE).to_i
end
def drivy_fee
(commission - insurance_fee - assistance_fee).to_i + rental.deductible_fee
end
def total
insurance_fee + assistance_fee + drivy_fee
end
private
attr_reader :rental
def commission
(commission_price.to_f * 0.3).to_i
end
def commission_price
total_price - rental.deductible_fee
end
def rental_length
rental.length
end
def total_price
rental.price
end
end
|
require 'digest'
module Digest
class RubySHA3 < Digest::Class
PILN = [10, 7, 11, 17, 18, 3, 5, 16,
8, 21, 24, 4, 15, 23, 19, 13,
12, 2, 20, 14, 22, 9, 6, 1]
ROTC = [ 1, 3, 6, 10, 15, 21, 28, 36,
45, 55, 2, 14, 27, 41, 56, 8,
25, 43, 62, 18, 39, 61, 20, 44]
RNDC = [0x0000000000000001, 0x0000000000008082, 0x800000000000808a,
0x8000000080008000, 0x000000000000808b, 0x0000000080000001,
0x8000000080008081, 0x8000000000008009, 0x000000000000008a,
0x0000000000000088, 0x0000000080008009, 0x000000008000000a,
0x000000008000808b, 0x800000000000008b, 0x8000000000008089,
0x8000000000008003, 0x8000000000008002, 0x8000000000000080,
0x000000000000800a, 0x800000008000000a, 0x8000000080008081,
0x8000000000008080, 0x0000000080000001, 0x8000000080008008]
def initialize hash_size = 512
@size = hash_size / 8
@buffer = ''
end
def << s
@buffer << s.unpack('C*').pack('C*')
self
end
alias update <<
def reset
# @buffer.clear # CHANGE: DO NOT CLEAR BUFFER AS WE NEED
self
end
def digest(data = nil)
if data
update(data)
value = finish
else
cloned = dup
value = cloned.finish
end
value
end
def hexdigest(data = nil)
value = digest(data)
value.unpack("H*").first
end
def inspect
"#<#{self.class}: #{hexdigest}>"
end
def finish
s = Array.new 25, 0
width = 200 - @size * 2
buffer_dup = @buffer.dup
buffer_dup << "\x01" << "\0" * (width - buffer_dup.size % width)
buffer_dup[-1] = (buffer_dup[-1].ord | 0x80).chr.unpack('C*').pack('C*')
0.step buffer_dup.size - 1, width do |j|
quads = buffer_dup[j, width].unpack 'Q*'
(width / 8).times do |i|
s[i] ^= quads[i]
end
keccak s
end
s.pack('Q*')[0, @size]
end
private
def keccak s
24.times.each_with_object [] do |round, a|
# Theta
5.times do |i|
a[i] = s[i] ^ s[i + 5] ^ s[i + 10] ^ s[i + 15] ^ s[i + 20]
end
5.times do |i|
t = a[(i + 4) % 5] ^ rotate(a[(i + 1) % 5], 1)
0.step 24, 5 do |j|
s[j + i] ^= t
end
end
# Rho Pi
t = s[1]
24.times do |i|
j = PILN[i]
a[0] = s[j]
s[j] = rotate t, ROTC[i]
t = a[0]
end
# Chi
0.step 24, 5 do |j|
5.times do |i|
a[i] = s[j + i]
end
5.times do |i|
s[j + i] ^= ~a[(i + 1) % 5] & a[(i + 2) % 5]
end
end
# Iota
s[0] ^= RNDC[round]
end
end
def rotate x, y
(x << y | x >> 64 - y) & (1 << 64) - 1
end
end
end
|
module Prov
class HandlesProvBlock
attr_reader :body,:commands,:triples
def initialize
@urinum=0
@commands=[]
end
def uri
RDF::URI url
end
def graph_uri
"http://www.amee.com/graph"
end
def author
nil
end
def newuri
@urinum+=1
RDF::URI "#{url}##{@urinum}"
end
def triples
@commands.map{|x| x.triples}.flatten(1)
end
private
def parse_body
# commands are bounded by prov:foo and semicolon
# pain to do this in ruby 1.8 without lookaround to do non-consuming splits
return unless body
lines=body.split(/[;]/) # was also on newline, trying without
# tokenize on whitespace
lines.each do |line|
$log.debug "Parsing #{line}"
begin
tokens=Shellwords.shellwords(line) # don't split whitespace inside quotes
rescue ArgumentError
# robustly try to do the right thing if apostrophe in middle of a word
line.gsub!(/\w'\w/,'') # handle didn't shouldn't it's cat's etc...
begin
tokens=Shellwords.shellwords(line)
rescue ArgumentError
line.gsub!(/\w'/,'') # handle dogs'
begin
tokens=Shellwords.shellwords(line)
rescue ArgumentError
tokens=line.split(' ')
end
end
end
reset_parser
tokens.each do |token|
handle_token(token)
end
command if @command
end
end
def handle_token(token)
if token=~/prov\:/
cname=token.sub(/prov\:/,'')
return if cname.blank? # means someone's put prov: without a subcommand.
# if there's already a command on this line, we reached end of arguments
command if @command
# and regardless of that, we've got a new command to start now.
@command=cname
else
# it's only an arg to a command if we're currently doing a command
@args.push token if @command
end
end
def reset_parser
@command=nil
@args=[]
end
def command
c=Command.create(self,@command,@args)
@commands.push(c) if c
reset_parser
end
end
end
|
@token = nil
@error = nil
When(/^the user pairs with BitPay(?: with a valid pairing code|)$/) do
claim_code = get_claim_code_from_server
pem = BitPay::KeyUtils.generate_pem
@client = BitPay::Client.new(api_uri: ROOT_ADDRESS, pem: pem, insecure: true)
@token = @client.pair_pos_client(claim_code)
end
When(/^the fails to pair with BitPay because of an incorrect port$/) do
pem = BitPay::KeyUtils.generate_pem
address = ROOT_ADDRESS.split(':').slice(0,2).join(':') + ":999"
client = BitPay::Client.new(api_uri: address, pem: pem, insecure: true)
begin
client.pair_pos_client("1ab2c34")
raise "pairing unexpectedly worked"
rescue => error
@error = error
true
end
end
Given(/^the user is authenticated with BitPay$/) do
@client = new_client_from_stored_values
end
Given(/^the user is paired with BitPay$/) do
raise "Client is not paired" unless @client.verify_token
end
Given(/^the user has a bad pairing_code "(.*?)"$/) do |arg1|
# This is a no-op, pairing codes are transient and never actually saved
end
Then(/^the user fails to pair with a semantically (?:in|)valid code "(.*?)"$/) do |code|
pem = BitPay::KeyUtils.generate_pem
client = BitPay::Client.new(api_uri: ROOT_ADDRESS, pem: pem, insecure: true)
begin
client.pair_pos_client(code)
raise "pairing unexpectedly worked"
rescue => error
@error = error
true
end
end
Then(/^they will receive an? (.*?) matching "(.*?)"$/) do |error_class, error_message|
raise "Error: #{@error.class}, message: #{@error.message}" unless Object.const_get(error_class) == @error.class && @error.message.include?(error_message)
end
|
$: << File.dirname(__FILE__)
$test_env = true
require "../lib/proforma"
describe "A Low level TextField" do
before do
class DerpForm < Form
@@derp_field = TextField.new("Herp some derps", :max_length=>2)
end
@derp_field = DerpForm.new.fields[0]
end
it "should assign its name based on the class variable name" do
@derp_field._noko_first(:input)[:name].should == 'derp_field'
end
it "should assign its id based on the class variable name" do
@derp_field._noko_first(:input)[:id].should == 'id_derp_field'
end
it "should base the field type on the assigning class" do
@derp_field._noko_first(:input)[:type].should == 'text'
end
it "should be able to template basic field types" do
@derp_field.to_html.should == "<input type=\"text\" name=\"derp_field\" id=\"id_derp_field\" />"
end
it "should generate its own labels" do
@derp_field.label_tag.should == "<label for=\"id_derp_field\">Herp some derps</label>"
@derp_field.label_text.should == "Herp some derps"
end
it "should re-insert values if validation fails" do
d = DerpForm.new(:derp_field=>"abc")
d._noko_first(:input)[:value].should == 'abc'
end
end
describe "A Checkbox field" do
before do
class UglinessForm < Form
@@ugly = CheckboxField.new("Check here if ugly")
@@stupid = CheckboxField.new("Check here if stupid")
def cleaned_form(datum)
raise FormValidationError.new("This form is never valid")
end
end
@ugliness_form = UglinessForm.new
@ugly_field = @ugliness_form.fields[0]
@stupid_field = @ugliness_form.fields[1]
end
it "should have the checkbox type" do
@ugly_field._noko_first(:input)[:type].should == "checkbox"
@stupid_field._noko_first(:input)[:type].should == "checkbox"
end
it "should generate its own labels" do
@stupid_field.label_text.should == "Check here if stupid"
@ugly_field.label_text.should == "Check here if ugly"
end
it "should give its label tag an input id based 'for'" do
@ugly_field._noko_label_tag[:for].should == "id_ugly"
@stupid_field._noko_label_tag[:for].should == "id_stupid"
end
it "should render correctly" do
@stupid_field.to_labeled_html.should == "<input type=\"checkbox\" name=\"stupid\" id=\"id_stupid\" /><label for=\"id_stupid\">Check here if stupid</label>"
end
it "should retain posted values" do
u = UglinessForm.new(:stupid => "on", :ugly=> "on")
#puts u.to_html
end
end
describe "A Low level Form" do
before do
class LoginForm < Form
@@username = TextField.new("Username")
@@password = TextField.new("Password", :html_attributes => {:class => :pw})
@@herp = "derp"
end
@login_form = LoginForm.new
end
it "should correctly report its fields in the defined order" do
fields_as_strings = @login_form.fields.map {|f| f.to_html}
fields_as_strings.should == [
"<input type=\"text\" name=\"username\" id=\"id_username\" />",
"<input class=\"pw\" type=\"text\" name=\"password\" id=\"id_password\" />",
]
end
it "should accept a hash of attributes" do
class OptInForm < Form
@@future_communications = CheckboxField.new("Would you like to receive future communications", :html_attributes => {:checked => :checked} )
end
@opt_in_form = OptInForm.new
fields_as_strings = @opt_in_form.fields.map {|f| f.to_html}
fields_as_strings.should == [
"<input checked=\"checked\" type=\"checkbox\" name=\"future_communications\" id=\"id_future_communications\" />"
]
end
end
describe "A Form containing RadioFields" do
before do
class GenderForm < Form
@@gender = RadioChoiceField.new("Choose your gender", ["Male", "Female"])
end
@gender_form = GenderForm.new
@gender_field = @gender_form.fields[0]
end
it "should create a fieldset with an id based on the class var" do
@gender_field._noko_first(:fieldset)[:id].should == 'id_gender'
end
it "should create a legend from the label text" do
@gender_field._noko_first(:legend).content.should == "Choose your gender"
end
end
describe "A Form containing ChoiceFields" do
before do
class FamilyForm < Form
@@surname = ChoiceField.new("Choose a family", ['Capulet', 'Montague'])
end
@family_form = FamilyForm.new
@surname_field = @family_form.fields[0]
end
it "should generate a list of html options" do
@surname_field._html_options.should == "<option value=\"Capulet\">Capulet</option><option value=\"Montague\">Montague</option>"
end
it "should generate a complete select field" do
field = @surname_field._noko_first(:select)
field[:id].should == @surname_field.html_id.to_s
field[:name].should == 'surname'
end
end
describe "A field with custom wrappers" do
before do
class CustomNameVarForm < Form
@@description_of_derps = TextField.new("Herp some derps")
@@gender_choice = RadioChoiceField.new("Choose your gender", ["Male", "Female"])
@@cat = CheckboxField.new("Are you a cat?", :html_attributes => {:checked => :checked} )
@@family = ChoiceField.new("Choose a family", ['Capulet', 'Montague', "Other"])
def redefine_defaults
{:hash_wrapper => :something}
end
end
end
it "should create 4 fields" do
b = CustomNameVarForm.new
b.fields.length.should == 4
end
it "should let the user configure the hash wrapper around name attributes" do
c = CustomNameVarForm.new
c.fields.each do |field|
#puts field.to_html
field.to_html.match(/name=\"something\[#{field.name}\]\"/).should_not be_nil
end
end
end
describe "A Textarea field" do
before do
class TextAreaForm < Form
@@bio = TextAreaField.new("Herp some derps", :help_text => "Fill in this form", :min_length => 2)
end
@form = TextAreaForm.new
@textarea = @form._noko_first(:textarea)
end
it "should render a <textarea> tag" do
@textarea.should_not be_nil
end
it "should not have a type attribute by default" do
@textarea[:type].should be_nil
end
it "should name itself properly" do
@textarea[:name].should == 'bio'
end
it "generate its own id" do
@textarea[:id].should == 'id_bio'
end
it "should regenerate values after posts" do
posted_form = TextAreaForm.new({:bio => 'a'})
posted_form.valid?.should be_false
posted_form._noko_first(:textarea).content.should == 'a'
end
end
|
class CreateIncidentworkflows < ActiveRecord::Migration[6.0]
def change
create_table :incidentworkflows do |t|
t.references :incident, null: false, foreign_key: true
t.references :workflowtemplate, null: false, foreign_key: true
t.timestamps
end
end
end
|
class DeploymentBroadcastJob < ApplicationJob
queue_as :default
def perform(status, user:)
DeploymentChannel.broadcast_to user, status: status
end
end
|
# Represents a grid column!
module Autogrid
class Column
# An unique String ID of this column
attr_accessor :id
# The name of this column, which should be human readable
attr_accessor :name
# todo: comment these
attr_accessor :html, :header_html, :visible, :hidden, :filter, :use_db,
:sortable, :sort_order, :format, :format_options, :always_visible
attr_reader :grid, :db_column, :db_table, :db_fullname
# Makes a new column!
# == Parameters
# * +grid+ - a Flexigrid object'
# * +id+ - The ID for this column
# * +name+ - an optional human readable name for this column. If one is not
# given, then one will automatically be generated.
def initialize(grid, id, name = nil)
@grid = grid
@id = id
@sortable = true
# Databaseize stuff
id_s = id.split('.')
@db_column = id_s.last
@db_table = id_s.count == 1 ? @grid.model_class.table_name : id_s[id_s.count - 2].tableize
@db_fullname = "`#{@db_table}`.`#{@db_column}`"
if name.nil?
if @grid.model.is_a? ActiveRecord::Relation
@name = @grid.model.klass.human_attribute_name(@db_column)
elsif @grid.model.is_a? ActiveRecord::Base
@name = @grid.model.class.human_attribute_name(@db_column)
else
raise "Grid model must be an ActiveRecord type of object!"
end
else
@name = name
end
# Defaults
@hidden = @visible = false
end
def to_sort
return 'asc' if @sort_order.blank? or @sort_order == 'DESC'
return 'desc'
end
def update!
end
def sortable?
@sortable
end
def sort_col?
!@sort_order.blank?
end
def render(actionView, mdl)
data = Misc::nested_send(mdl, @id)
return actionView.capture(data,mdl,&filter) unless filter.blank?
if !@format.nil? and Flexigrid::Formatter.respond_to? @format
return Flexigrid::Formatter.send(@format, actionView, data, @format_options)
end
return data
end
# Whether this column is the one being used for sorting
def sort?
@grid.sort == self
end
# Whether this column is hidden by default
def hidden?
@hidden
end
# Whether this column should currently be displayed
def visible?
@visible
end
def always_visible?
@always_visible
end
end
end
|
class KeyValueWidget
attr_accessor :value
def initialize(x, y, label, value)
raise 'Cannot initialize key value widget when x is nil' unless x
raise 'Cannot initialize key value widget when y is nil' unless y
raise 'Cannot initialize key value widget when label is nil' unless label
raise 'Cannot initialize key value widget when value is nil' unless value
@x = x
@y = y
@label = label
@value = value
end
def draw(display)
raise 'Cannot draw text when display is nil' unless display
x = @x
@label.each_char do |c|
display.draw x, @y, c
x += 1
end
display.draw x, @y, ':'
x += 1
display.draw x, @y, ' '
x += 1
@value.each_char do |c|
display.draw x, @y, c
x += 1
end
end
end
|
class Substring
def initialize
@dictionary = ["below","down","go","going","horn","how","howdy","it","i","low","own","part","partner","sit"]
end
def user_input(string)
substrings(string,@dictionary)
end
def substrings(string, dict_array)
my_hash = {}
arr_word = string.split(" ")
arr_word.each do |current_word|
i = 1
current_word.downcase!
dict_array.each do |dict_word|
if(current_word =~ /#{dict_word}/ )
if(my_hash.has_key?(dict_word))
my_hash[dict_word] += 1
i = my_hash[dict_word]
end
my_hash[dict_word] = i
end
end
end
return my_hash.sort.to_h
end
end
ss = Substring.new
user_word = "Howdy partner, sit down! How's it going?"
result = ss.user_input(user_word)
puts result |
module Hpricot
# :stopdoc:
class Doc
attr_accessor :children
def initialize(children)
@children = children ? children.each { |c| c.parent = self } : []
end
def output(out)
@children.each do |n|
n.output(out)
end
out
end
end
class BaseEle
attr_accessor :raw_string, :parent
def html_quote(str)
"\"" + str.gsub('"', '\\"') + "\""
end
end
class Elem
attr_accessor :stag, :etag, :children
def initialize(stag, children=nil, etag=nil)
@stag, @etag = stag, etag
@children = children ? children.each { |c| c.parent = self } : []
end
def empty?; @children.empty? end
[:name, :attributes, :parent].each do |m|
[m, "#{m}="].each { |m2| define_method(m2) { |*a| @stag.send(m2, *a) } }
end
def output(out)
if empty? and ElementContent[@stag.name] == :EMPTY
@stag.output(out, :style => :empty)
else
@stag.output(out)
@children.each { |n| n.output(out) }
@stag.output(out, :style => :end)
end
out
end
end
class STag < BaseEle
def initialize(name, attributes=nil)
@name = name.downcase
if attributes
@attributes = attributes.inject({}) { |hsh,(k,v)| hsh[k.downcase] = v; hsh }
end
end
attr_accessor :name, :attributes
def attributes_as_html
if @attributes
@attributes.map do |aname, aval|
" #{aname}" +
(aval ? "=#{html_quote(aval)}" : "")
end.join
end
end
def output(out, opts = {})
out <<
case opts[:style]
when :end
"</#{@name}>"
else
"<#{@name}#{attributes_as_html}" +
(opts[:style] == :empty ? " /" : "") +
">"
end
end
end
class ETag < BaseEle
def initialize(qualified_name)
@name = qualified_name
end
attr_reader :name
end
class BogusETag < ETag
def output(out); end
end
class Text < BaseEle
def initialize(text)
@content = text
end
attr_reader :content
def output(out)
out << @content
end
end
class XMLDecl < BaseEle
def initialize(version, encoding, standalone)
@version, @encoding, @standalone = version, encoding, standalone
end
attr_reader :version, :encoding, :standalone
def output(out)
out <<
"<?xml version=\"#{@version}\"" +
(@encoding ? " encoding=\"#{encoding}\"" : "") +
(@standalone != nil ? " standalone=\"#{standalone ? 'yes' : 'no'}\"" : "") +
"?>"
end
end
class DocType < BaseEle
def initialize(name, pubid, sysid)
@name, @public_id, @system_id = name, pubid, sysid
end
attr_reader :name, :public_id, :system_id
def output(out)
out <<
"<!DOCTYPE #{@name} " +
(@public_id ? "PUBLIC \"#{@public_id}\"" : "SYSTEM") +
(@system_id ? " #{html_quote(@system_id)}" : "") + ">"
end
end
class ProcIns < BaseEle
def initialize(target, content)
@target, @content = target, content
end
attr_reader :target, :content
def output(out)
out << "<?#{@target}" +
(@content ? " #{@content}" : "") +
"?>"
end
end
class Comment < BaseEle
def initialize(content)
@content = content
end
attr_reader :content
def output(out)
out << "<!--#{@content}-->"
end
end
# :startdoc:
end
|
class Backbone::ThemesController < ApplicationController
def index
render :json => Theme.where(:status => :active).all
end
end |
class AddPaperTrailTables < ActiveRecord::Migration[5.0]
def change
create_table :paper_trail_versions do |t|
t.string :item_type
t.integer :item_id, null: false
t.string :event, null: false
t.string :whodunnit
t.text :object
t.datetime :created_at
end
add_index :paper_trail_versions, %i[item_type item_id]
create_table :version_associations do |t|
t.integer :version_id
t.string :foreign_key_name, null: false
t.integer :foreign_key_id
end
add_index :version_associations, [:version_id]
add_index :version_associations,
%i[foreign_key_name foreign_key_id],
name: 'index_version_associations_on_foreign_key'
end
end
|
module Exercise2
class Solution
attr_reader :numbers, :iterations, :calculation_results
def initialize(number, with_print = false)
@n = number
@calculation_results = []
@iterations = 0
@with_print = with_print
end
def run
while @n != 495 && @n != 0
# main loop calculations
n0 = @n
min, max = calculate_min_max(@n)
@n1 = max
@n2 = min
@n = @n1 - @n2
@iterations += 1
# used for debug
print_iteration(max, min, n0) if @with_print
store_iteration_result
end
@n
end
private
def number_plus_10(n)
output = []
while n < 1000
output << n
n = n + 10
end
output
end
def store_iteration_result
@calculation_results << prepare_output_digits(@n)
end
def print_iteration(max, min, n0)
puts "#{@iterations}- Number: #{prepare_output_digits(n0)}: #{prepare_output_digits(max)} - #{prepare_output_digits(min)} = #{prepare_output_digits(@n)}"
end
def calculate_min_max(number)
calculate_permutation(number).minmax
end
def calculate_permutation(number)
digits = calculate_digits(number)
digits.permutation.to_a.map { |e| e.join("").to_i }
end
def calculate_digits(number)
digits = number.digits.reverse
case digits.length
when 3 then digits
when 2 then digits.unshift(0)
when 1 then digits.unshift(0).unshift(0)
else raise StandardError, "Invalid Integer"
end
end
def prepare_output_digits(number)
calculate_digits(number).join("")
end
end
end
|
class Project < ActiveRecord::Base
STATUSES = [:ongoing, :finished, :stopped]
has_many :story
#validations
validates :title, presence: true
validates :status, presence: true, numericality: {
greater_than_or_equal_to:0, less_than: STATUSES.length
}
end
|
class HomeController < ApplicationController
before_filter :require_user
before_filter :require_admin, only: [:make_chore_auction_form]
before_filter :clear_admin, only: [:make_chore_auction]
def my_chores
#grabs user data to display chores in the template
@user = current_user
respond_to do |format|
format.html # my_chores.html.erb
format.json { render :json => @user }
end
end
def chore_market
#retrieves all chores in the view specified
#(open, all, or closed)
@view = params[:view] ? params[:view] : 'open'
#@chores = Chore.where(:auctions_count => 1)
@shared_chores=SharedChore.all
@shared_chores.keep_if { |sc| sc.active? }
@chores = Chore.where("auctions_count=1 OR bounties_count=1")
#sorts chores, puts open on top
#sorts open by which expires soonest,
#and closed by which expired most recently
sorted_open=@chores.find_all{|chore| chore.open?}.sort{|a,b| a.end_date <=> b.end_date}
sorted_closed=@chores.find_all{ |chore| not chore.open? }.sort{ |b,a| a.end_date <=> b.end_date}
@chores = sorted_open+sorted_closed
@open_shared = @chores.select { |c| c.is_a? SharedChore and not c.active? }
@chores.keep_if { |c| not c.is_a? SharedChore }
end
def make_chore_auction_form
#makes new chore object for form structure
@chore = Chore.new
#also makes a sharedchore to deal with forms_for
@shared_chore = SharedChore.new
#makes auction object and attaches it
@auction = Auction.new
@auction.chore = @chore
respond_to do |format|
format.html # make_chore_auction_form.html.erb
format.json { render :json => @user }
end
end
def make_chore_auction
@auction = Auction.new(params[:chore][:auction])
chore_params=params[:chore]
chore_type = params[:chore_type]
chore_params[:auction]=@auction
@chore = (params[:shared] and params[:shared].to_b) ? SharedChore.new(chore_params) : Chore.new(chore_params)
@auction.chore = @chore
@chore.auction = @auction
Auction.transaction do
respond_to do |format|
if @auction.save and @chore.save
@auction.delay(:run_at => @auction.expiration_date).close
format.html { redirect_to('/home/chore_market', :notice => 'Chore auction created.') }
format.json { render :json }
else
format.html { redirect_to('/home/chore_market', :notice => 'Could not create chore auction.') }
format.json { render :json => @user_session.errors, :status => :unprocessable_entity }
end
end
end
@scheduler = ChoreScheduler.new(:respawn_time => params[:respawn], default_bids: {} )
@scheduler.chore = @chore
@chore.chore_scheduler = @scheduler
@scheduler.save
@chore.save
if params[:respawn].to_i != 0
run_at = Time.now + @scheduler.respawn_time
@scheduler.delay(run_at: run_at).schedule_next(run_at)
end
end
def give_chorons_form
#gets user id from url parameters
@user = User.find(params[:user_id])
#displays form asking for amount of chorons
respond_to do |format|
format.html # give_chorons_form.html.erb
format.json { render :json => @user }
end
end
def give_chorons
#uses parameters to find out
#how many chorons were given and to whom
@chorons = params[:user][:chorons].to_i
@recipient = User.find(params[:user][:user_id])
@giver = current_user
#processes request in database
success = @giver.give_chorons(@recipient, @chorons)
#if both objects saved, display success
respond_to do |format|
if success
format.html { redirect_to(@recipient, :notice => 'Gift successful.') }
format.json { render :json }
else
format.html { redirect_to(@recipient, :notice => 'Gift could not be processed.') }
format.json { render :json => @user_session.errors, :status => :unprocessable_entity }
end
end
end
def get_preferences_list
@prefs = current_user.bid_prefs
end
def show_preference
@user= current_user
respond_to do |format|
format.html # make_chore_auction_form.html.erb
format.json { render :json => @user }
end
end
def edit_preference
@user=current_user
@user.bid_prefs[Integer(params[:scheduler_id])]=
{value: Integer(params[:value]),manual: params[:manual]}
unless params[:manual]
@user.auto_preferences([ChoreScheduler.find(params[:scheduler_id])])
end
respond_to do |format|
if @user.save
format.html { redirect_to('/home/preferences', :notice => 'Preferences edited.') }
format.json { render :json }
else
format.html { redirect_to('/home/preferences', :notice => 'Could not edit preference.') }
format.json { render :json => @user_session.errors, :status => :unprocessable_entity }
end
end
end
def update_preferences
@user=current_user
params[:amounts].each_pair {
| sid, pref |
cut = params[:cuts] ? params[:cuts][sid] : nil
cut = (cut == "") ? nil : cut
if @user.bid_prefs[Integer(sid)][:value] != Integer(pref) or (cut and @user.bid_prefs[Integer(sid)][:cut] != Integer(cut))
@user.bid_prefs[Integer(sid)].update({value: Integer(pref), manual: true})
if cut
@user.bid_prefs[Integer(sid)][:cut] = Integer(cut)
end
end
}
respond_to do |format|
if @user.save
format.html { redirect_to('/home/preferences', :notice => 'Preferences updated.') }
format.json { render :json }
else
format.html { redirect_to('/home/preferences', :notice => 'Could not update preferences.') }
format.json { render :json => @user_session.errors, :status => :unprocessable_entity }
end
end
end
def clear_preferences
@user=current_user
schedulers = @user.bid_prefs.keys
schedulers.map! {
|s|
ChoreScheduler.find s
}
@user.bid_prefs.clear
@user.auto_preferences schedulers
respond_to do |format|
if @user.save
format.html { redirect_to('/home/preferences', :notice => 'Preferences cleared.') }
format.json { render :json }
else
format.html { redirect_to('/home/preferences', :notice => 'Could not clear preferences.') }
format.json { render :json => @user_session.errors, :status => :unprocessable_entity }
end
end
end
def give_chore_form
#gets user id from url parameters
#displays form asking for amount of chorons
end
def give_chore
#uses parameters to find out
#how many chorons were given and to whom
#processes request in database
#if both objects saved, display success
end
end
|
require "net/ssh"
class ExecWithStatus
def initialize(ssh, command)
@command = command
@channel = ssh.open_channel(&method(:channel_opened))
@channel[:out] = ""
end
def result
@channel[:out]
end
def status
@status
end
private
def channel_opened(channel)
channel.exec(@command)
channel.on_data(&method(:channel_data))
channel.on_extended_data(&method(:channel_extended_data))
channel.on_request("exit-status", &method(:exit_status))
end
def channel_data(channel, data)
channel[:out] << data
end
def channel_extended_data(channel, type, data)
channel[:out] << data
end
def exit_status(channel, request)
@status = request.read_long
puts "`#{@command}' failed with #{@status}"# unless status == 0
end
end
class Net::SSH::Connection::Session
def exec_with_status(command)
ExecWithStatus.new(self, command)
end
end
class SSHWorker
attr_reader :buffer
# connect and get info, stays on?
def initialize(host, user, comm = nil)
ssh_opts = {
:port => host.port,
:config => true,
:keys => "~/.ssh/id_rsa",
:verbose => :debug,
:timeout => 20
#:paranoid => true
}
ssh_opts.merge!(:password => host.pass) if host.pass && host.pass != ""
p ssh_opts
Net::SSH.start(host.addr, user, ssh_opts) do |ssh|
# puts hostname = ssh.exec_with_status("hostname").result
if comm
ex = ssh.exec_with_status(comm)
ssh.loop
@buffer = ex.result
else
@result = { }
for sample in Stat::comm(host)
puts "Executing #{sample}"
@result[sample[0]] = ssh.exec_with_status(sample[1])
end
ssh.loop
@result.map { |k, v| @result[k] = v.result}
s = host.stats.create(@result)
end
#s.save!
end
end
end
# puts "Connecting to #{host}"
# @buffer = ""
# @channels = []
# @user = host.user
# @options = {
# :port => host.port || 22,
# :keys => user.keys.first,
# :password => host.pass,
# :verbose => :debug
# }
# connect
# do_get("uptime")
# @session.loop
# @session.close
# end
# def connect
# if @options[:password]
# @options[:auth_methods] = [ "password","keyboard-interactive" ]
# end
# @session = Net::SSH.start(@host, @user, @options)
# puts "Connected!"
# rescue SocketError, Errno::ECONNREFUSED => e
# puts "!!! Could not connect to #{@host}. Check to make sure that this is the correct url."
# # puts $! if $DBG > 0
# exit
# rescue Net::SSH::AuthenticationFailed => e
# puts "!!! Could not authenticate on #{@host}. Make sure you have set the username and password correctly. Or if you are using SSH keys make sure you have not set a password."
# # puts $! if $DBG > 0
# exit
# end
# def do_get(comm)
# puts "Trying #{comm}"
# @ch = @session.open_channel do |c|
# puts "Opening channel..#{@session.host}"
# #c.request_pty :want_reply => true
# c.on_data do |ch, data|
# @buffer << data
# parse_line(data)
# end
# #ch.exec comm
# c.do_success do |ch|
# c.exec "#{comm}"# #{file} "
# end
# c.do_failure do |ch|
# ch.close
# end
# c.on_extended_data do |ch, data|
# puts "STDERR: #{data}\n"
# end
# c.do_close do |ch|
# ch[:closed] = true
# end
# puts "Pushing #{@session}\n"# if($VRB > 0 || $DBG > 0)
# @channels.push(c)
# end
# end
# end
|
class UsersController < ApplicationController
before_action :authorize_user
skip_before_action :verify_authenticity_token
def new
@user = User.new
end
def create
@list = List.find_by_id(params[:list_id])
@user = User.find_or_create_by_filtered_params(user_params)
@user.assign_invitation_token unless @user.persisted?
if @user.save
@user.invite!(@list)
redirect_to @list
else
render :new
end
end
def account
@user = current_user
end
def update
@user = current_user
if @user.update_with_password(user_params)
redirect_to session[:forwarding_url] || account_path
else
render :account
end
end
private
def user_params
params.require(:user).permit(
:phone,
:email,
:username,
:dark_mode,
:password,
:password_confirmation,
:current_password
).reject { |_, v| v.blank? }
end
end
|
require 'chefspec'
require 'chefspec/berkshelf'
require_relative 'support/example_groups/provider_example_group'
require_relative 'support/example_groups/resource_example_group'
RSpec.configure do |config|
config.color = true # Use color in STDOUT
config.formatter = :documentation # Use the specified formatter
config.log_level = :error # Avoid deprecation notice SPAM
config.include Chef::ProviderExampleGroup,
type: :provider,
example_group: lambda { |example_group, metadata|
metadata[:type].nil? && %r{spec/providers/} =~ example_group[:file_path]
}
config.include Chef::ResourceExampleGroup,
type: :resource,
example_group: lambda { |example_group, metadata|
metadata[:type].nil? && %r{spec/resources/} =~ example_group[:file_path]
}
end
def load_resource(cookbook, lwrp)
require 'chef/resource/lwrp_base'
name = class_name_for_lwrp(cookbook, lwrp)
unless Chef::Resource.const_defined?(name)
Chef::Resource::LWRPBase.build_from_file(
cookbook,
File.join(File.dirname(__FILE__), %W(.. resources #{lwrp}.rb)),
nil
)
end
end
def load_provider(cookbook, lwrp)
require 'chef/provider/lwrp_base'
name = class_name_for_lwrp(cookbook, lwrp)
unless Chef::Provider.const_defined?(name)
Chef::Provider::LWRPBase.build_from_file(
cookbook,
File.join(File.dirname(__FILE__), %W(.. providers #{lwrp}.rb)),
nil
)
end
end
def class_name_for_lwrp(cookbook, lwrp)
require 'chef/mixin/convert_to_class_name'
Chef::Mixin::ConvertToClassName.convert_to_class_name(
Chef::Mixin::ConvertToClassName.filename_to_qualified_string(cookbook, lwrp)
)
end
|
require_dependency "usercommunications/application_controller"
module Usercommunications
class UsermaildataController < ApplicationController
before_action :set_usermaildatum, only: [:show, :edit, :update, :destroy]
# GET /usermaildata
def index
@usermaildata = Usermaildatum.all
end
# GET /usermaildata/1
def show
end
# GET /usermaildata/new
def new
@usermaildatum = Usermaildatum.new
end
# GET /usermaildata/1/edit
def edit
end
# POST /usermaildata
def create
@usermaildatum = Usermaildatum.new(usermaildatum_params)
if @usermaildatum.save
redirect_to @usermaildatum, notice: 'Usermaildatum was successfully created.'
else
render :new
end
end
# PATCH/PUT /usermaildata/1
def update
if @usermaildatum.update(usermaildatum_params)
redirect_to @usermaildatum, notice: 'Usermaildatum was successfully updated.'
else
render :edit
end
end
# DELETE /usermaildata/1
def destroy
@usermaildatum.destroy
redirect_to usermaildata_url, notice: 'Usermaildatum was successfully destroyed.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_usermaildatum
@usermaildatum = Usermaildatum.find(params[:id])
end
# Only allow a list of trusted parameters through.
def usermaildatum_params
params.require(:usermaildatum).permit(:username, :useremail, :content)
end
end
end
|
require 'rails_helper'
RSpec.describe LikesController, type: :controller do
before do
@user = create(:user)
@secret = create(:secret, user: @user)
@like = create(:like, secret: @secret, user: @user)
end
context "when not logged in " do
before do
session[:user_id] = nil
end
it "cannot create a like" do
post :create, like: build(:like)
expect(response).to redirect_to(new_session_path)
end
it "cannot destroy a like" do
delete :destroy, id: @like
expect(response).to redirect_to(new_session_path)
end
end
context "when signed in as the wrong user" do
before do
@user2 = create(:user, first_name: "choo", last_name: "boo", email: "more.choi.boi@dojo.com", password: "password", password_confirmation: "password")
end
it "shouldn't be able to destroy a like" do
delete :destroy, id: @like
expect(response).to_not be_success
end
end
end |
module PayoneerApiClient
class Balance
class << self
def status
PayoneerApiClient.make_api_request(METHOD_NAME[:balance], :get)
end
end
end
end
|
class Cliente < ActiveRecord::Base
def self.search(search, page)
where(['upper(nombre) like ?',
"%#{search}%".upcase]).paginate(page: page, per_page: 3).order("nombre")
end
end |
module AuthForum
class OrderMailer < ApplicationMailer
def order_confirm(order)
@order = order
mail(to: order.email, subject: 'Your order has been Confirmed')
end
end
end
|
## Staxfile DSL commands
module Stax
module Dsl
def stack(name, opt = {})
opt = {groups: @groups}.merge(opt) # merge with defaults
Stax.add_stack(name, opt)
end
def command(*args)
Stax.add_command(*args)
end
## temporarily change default list of groups
def group(*groups, &block)
@groups = groups
yield
@groups = nil
end
end
end
## add main object singleton methods
extend Stax::Dsl |
require 'spec_helper'
describe 'restaurants index page' do
context 'no restaurants have been added' do
it 'should display a message' do
visit '/restaurants'
expect(page).to have_content 'No restaurants yet'
end
end
end
describe 'creating a restaurant' do
context 'logged out' do
it 'takes us to the sign up page' do
visit '/restaurants'
click_link 'Create a restaurant'
expect(page).to have_content 'Sign up'
end
end
context 'logged in' do
before do
user = User.create(email: 'scott@d.com', password: '123454', password_confirmation: '123454')
login_as user
end
it 'adds it to the restaurants index' do
visit '/restaurants/new'
fill_in 'Name', with: 'McDonalds'
fill_in 'Address', with: 'City Road, London'
fill_in 'Cuisine', with: 'Chicken'
click_button 'Create Restaurant'
expect(current_path).to eq '/restaurants'
expect(page).to have_content 'McDonalds'
end
end
end
describe ' editing a restaurant' do
before {Restaurant.create(name: 'KFC', address: '1High St, London', cuisine: 'chicken')}
# context 'logged out' do
# it 'does not show the review form' do
# visit '/restaurants'
# expect(page).not_to have_link 'Edit KFC'
# end
# end
# context 'logged in' do
it 'saves the change to the restaurant' do
visit '/restaurants'
click_link 'Edit KFC'
fill_in 'Name', with: 'Kentucky Fried Chicken'
click_button 'Update Restaurant'
expect(current_path).to eq '/restaurants'
expect(page).to have_content 'Kentucky Fried Chicken'
end
# end
end
describe 'deleting a restaurant' do
before {Restaurant.create(name: 'Chicken Cottage', address: '2High St, London', cuisine: 'chicken')}
it'destroys a restaurant' do
visit '/restaurants'
click_link 'Delete Chicken Cottage'
expect(page).not_to have_content 'Chicken Cottage'
expect(page).to have_content 'Restaurant DESTROYED'
end
end
describe 'user can only enter valid data' do
context 'user enters invalid data' do
it 'does not add it to the restaurants index' do
visit '/restaurants/new'
fill_in 'Name', with: 'mcDonalds'
fill_in 'Address', with: 'lowercase'
# no cuisine fill_in
click_button 'Create Restaurant'
expect(page).to have_content 'errors'
end
end
end
|
class Repository < ActiveRecord::Base
has_many :votes
def self.display_order_by_score
self.order("score DESC").all
end
def self.display_order_by_pushed_at
self.order("repos_pushed_at DESC, score DESC").all
end
def vote(user)
return nil unless user
self.vote_count = self.votes.count + 1
self.score = self.culc_score
self.votes.build(:user_id => user.id)
self
end
def voted?(user)
self.votes.find_by_user_id(user) ? true : false
end
def culc_score
(self.vote_count * 5) + self.watchers + self.forks
end
end
|
require 'spec_helper'
describe Redemption do
let(:negative_points_redemption) do
FactoryGirl.build(:redemption, {
:points => - 50
})
end
let(:redemption) do
Redemption.new
end
let(:normal_redemption) do
FactoryGirl.create(:redemption)
end
let(:hacker) do
FactoryGirl.create(:hacker)
end
before do
Redemption.any_instance.stub(:hacker_remaining_points).and_return(700)
end
context 'associations' do
it 'should have a user which is instance of hacker' do
redemption.build_user.should be_kind_of(Hacker)
end
end # associations
context 'validations' do
it 'should not allow negative points' do
negative_points_redemption.should_not be_valid
negative_points_redemption.errors[:points].should be_present
end
end # validations
describe '#cancel!' do
it 'should produce a cancel object' do
normal_redemption.cancel.should be_blank
normal_redemption.cancel!.should be_true
normal_redemption.cancel.should be_present
end
it 'should allow anonym cancel' do
normal_redemption.cancel!.should be_true
normal_redemption.cancel.user.should be_blank
end
it 'should allow to cancel as user' do
normal_redemption.cancel!(hacker).should be_true
normal_redemption.cancel.user.should be(hacker)
end
end # #cancel!
end
|
# == Schema Information
#
# Table name: questions
#
# id :integer not null, primary key
# question_text :string
# created_at :datetime not null
# updated_at :datetime not null
# correct_answer_id :integer
#
class Question < ApplicationRecord
validates :question_text, presence: true
belongs_to :correct_answer, class_name: Answer
has_many :answers
def set_correct_answer_as(answer)
update_attributes(correct_answer: answer)
end
end
|
class AddSanitanizedUrlToShortUrls < ActiveRecord::Migration[5.2]
def change
add_column :short_urls, :sanitanized_url, :string
end
end
|
require 'jipcode'
require 'uri'
require 'net/http'
require 'zip'
require 'nkf'
module Jipcode
module JapanPost
ZIPCODE_URLS = {
general: 'https://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip'.freeze,
company: 'https://www.post.japanpost.jp/zipcode/dl/jigyosyo/zip/jigyosyo.zip'.freeze
}.freeze
ZIPCODE_FILES = {
general: 'KEN_ALL.CSV'.freeze,
company: 'JIGYOSYO.CSV'.freeze
}.freeze
def update
download_all
import_all
# データの更新月を記録する
File.open('zipcode/current_month', 'w') { |f| f.write(Time.now.strftime('%Y%m')) }
end
def download_all
ZIPCODE_URLS.each do |type, url|
url = URI.parse(url)
http = Net::HTTP.new(url.host, 443)
http.use_ssl = true
res = http.get(url.path)
File.open("zipcode/#{type}.zip", 'wb') { |f| f.write(res.body) }
end
end
def import_all
File.rename(ZIPCODE_PATH, 'zipcode/previous') if File.exist?(ZIPCODE_PATH)
Dir.mkdir(ZIPCODE_PATH)
# 事業所のデータには都道府県、市区町村、町域、番地のカナが与えられていない
# そのため、郵便番号情報から、都道府県、市区町村、町域のカナ読みを持っていきたいため、hashに保存しておく
kana_dict = Hash.new ""
zipcodes = unpack(:general)
import(zipcodes) do |row|
zipcode = row[2] # 郵便番号
prefecture = row[6] # 都道府県
city = row[7] # 市区町村
town = row[8] # 町域
prefecture_kana = row[3] # 都道府県カナ
city_kana = row[4] # 市区町村カナ
town_kana = row[5] # 町域カナ
kana_dict[prefecture] = prefecture_kana
kana_dict[city] = city_kana
[zipcode, prefecture, city, town, prefecture_kana, city_kana, town_kana]
end
zipcodes = unpack(:company)
import(zipcodes) do |row|
zipcode = row[7] # 郵便番号
prefecture = row[3] # 都道府県
city = row[4] # 市区町村
town = row[5] + row[6] # 町域 + 番地
prefecture_kana = kana_dict[prefecture]
city_kana = kana_dict[city]
town_kana = "" # [MEMO] 事業所データの町域番地に対してのカナは提供しない
[zipcode, prefecture, city, town, prefecture_kana, city_kana, town_kana]
end
FileUtils.rm_rf('zipcode/previous')
rescue => e
FileUtils.rm_rf(ZIPCODE_PATH)
File.rename('zipcode/previous', ZIPCODE_PATH) if File.exist?('zipcode/previous')
raise e, '日本郵便のデータを読み込めませんでした。'
end
# Private
def unpack(type)
content = ::Zip::File.open("zipcode/#{type}.zip") do |zip_file|
entry = zip_file.glob(ZIPCODE_FILES[type]).first
raise '日本郵便のファイルからデータが見つかりませんでした。' unless entry
entry.get_input_stream.read
end
# 文字コードをSHIFT JISからUTF-8に変換
NKF.nkf('-w -Lu', content)
end
def import(zipcodes)
duplicated_row = false
CSV.parse zipcodes do |row|
address = yield(row)
puts row unless address
town = address[3]
town_kana = address[6]
if duplicated_row
duplicated_row = false if town.end_with?(')')
next
else
duplicated_row = true if town.include?('(') && !town.include?(')')
end
# 町域等に含まれる曖昧な表記を削除
unless town.include?('私書箱')
address[3] = town.sub(/((.+|以下に掲載がない場合)$/, '')
address[6] = town_kana.sub(/((.+|イカニケイサイガナイバアイ)$/, '')
end
# 町域等の内容が市区町村の内容と重複する場合、空にする
if town.include?('の次に番地がくる場合') || town.include?('一円')
address[3] = nil
address[6] = nil
end
# 10万件以上あるので郵便番号上3桁ごとに分割
filepath = "#{ZIPCODE_PATH}/#{address[0][0..2]}.csv"
open(filepath, 'a') { |f| f.write("#{address.join(',')}\n") }
end
end
module_function :update, :download_all, :import_all, :unpack, :import
private_class_method :unpack, :import
end
end
|
# encoding: utf-8
class Departamento < ActiveRecord::Base
# Valida la precensia de los campos
validates_presence_of :departamento
# relacion de 1 a varios con documentos
has_many :clientes
# metodo que por defecto presenta el string
def to_s
departamento
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure(2) do |config|
config.vm.box = "12wrigja/LabyrinthServer"
config.vm.network "forwarded_port", guest: 4567, host: 4567
config.vm.network "forwarded_port", guest: 5005, host: 5005
config.vm.network "private_network", ip: "192.168.60.10"
config.vm.synced_folder ".", "/home/vagrant/LabyrinthServer"
config.vm.synced_folder "../HappyTweet/.", "/home/vagrant/HappyTweet"
config.vm.provider "virtualbox" do |v|
v.memory=2048
end
end
|
# frozen_string_literal: true
class Event < ApplicationRecord
include DateRange
validates_with EventSeasonValidator
belongs_to :user, optional: true
def self.ical(events = includes(:user))
Icalendar::Calendar.new.tap do |cal|
cal.prodid = '-//wereb.us//moretti.camp//EN'
events.each { |event| cal.add_event event.ical }
end
end
def display_title
title.presence || user.try(:first_name)
end
def full_title
"#{display_title} (#{date_range_words})"
end
# rubocop:disable Metrics/AbcSize
def ical
Icalendar::Event.new.tap do |e|
e.uid = "#{id}@moretti.camp"
e.status = 'CONFIRMED'
e.dtstart = Icalendar::Values::Date.new(start_date)
e.dtend = Icalendar::Values::Date.new(end_date + 1.day)
e.summary = display_title
e.description = description
e.created = created_at.to_fs(:ics)
e.last_modified = updated_at.to_fs(:ics)
end
end
# rubocop:enable Metrics/AbcSize
end
|
class PagesController < ApplicationController
layout 'admin'
before_filter :confirm_admin
before_filter :load_nav
def index
list
render('list')
end
def list
@pages = Page.sort
end
def show
@page = Page.find(params[:id])
@items = @page.items.sort
end
def new
@page = Page.new(:title => 'New Page')
@page_count = Page.count + 1
end
def create
# get position
@page = Page.new(params[:page])
if @page.save
# change position
flash[:notice] = "Page created successfully."
redirect_to(:action => 'list')
else
# save fails, redirect back to new
@page_count = Page.count + 1
render('new')
end
end
def edit
@page = Page.find(params[:id])
@page_count = Page.count
end
def update
# get position
@page = Page.find(params[:id])
if @page.update_attributes(params[:page])
#change position
flash[:notice] = "Page edited successfully."
redirect_to(:action => 'show', :id => @page.id)
else
@page_count = Page.count
render('edit')
end
end
def delete
@page = Page.find(params[:id])
end
def destroy
page = Page.find(params[:id])
#remove position
page.destroy
flash[:notice] = "Page deleted successfully."
redirect_to(:action => 'list')
end
end
|
# frozen_string_literal: true
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :authenticate_user!
before_action :configure_permitted_parameters, if: :devise_controller?
layout :layout_except_login
protected
def require_admin
redirect_to events_path unless current_user.admin
end
def configure_permitted_parameters
devise_parameter_sanitizer.permit :invite, keys: %i[first_name last_name]
devise_parameter_sanitizer.permit :account_update, keys: %i[first_name last_name email_updates
calendar_access_token]
end
def layout_except_login
user_signed_in? ? 'application' : 'login'
end
end
|
require 'test_helper'
describe "SuperFormatter::Tcat" do
before do
@spreadsheet = SuperSpreadsheet::Loader.new("test/support/tcat/export.csv").tap { |s| s.call }
@service = SuperFormatter::Tcat::Import.new(@spreadsheet).tap { |s| s.call }
end
should "#result.length = 34" do
assert_equal 34, @service.result.length
end
describe "第一個 row" do
before do
@row = @service.result[0]
end
should "#global_order_id = MB40881" do
assert_equal 'MB40881', @row.global_order_id
end
should "#recipient = 黃齡萱" do
assert_equal '黃齡萱', @row.recipient
end
should "#mobile = 0977481414" do
assert_equal '0977481414', @row.mobile
end
should "#tracking_code = 625270211891" do
assert_equal '625270211891', @row.tracking_code
end
end
describe "第2個 row" do
before do
@row = @service.result[1]
end
should "#global_order_id = MB40882" do
assert_equal 'MB40882', @row.global_order_id
end
should "#recipient = 翁采慧" do
assert_equal '翁采慧', @row.recipient
end
should "#mobile = 0907343512" do
assert_equal '0907343512', @row.mobile
end
should "#tracking_code = 625270211900" do
assert_equal '625270211900', @row.tracking_code
end
end
end
|
Rails.application.routes.draw do
namespace :api do
resources :departments do
resources :products
end
end
end
|
class UsersController < ApplicationController
before_action :find_user, only: [:show, :edit]
before_action :current_user
def index
@users = User.all
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
flash[:status] = "success"
flash[:result_text] = "User added!"
redirect_to users_path
else
flash.now[:alert] = @user.errors
render :new
end
end
def show
@user = User.find_by(id: params[:id])
head :not_found unless @user
@products = @user.products
end
def edit
end
def update
if @user.update(user_params)
flash[:status] = "success"
flash[:result_text] = "#{@user.username} updated!"
redirect_to user_path(params[:id])
else
render :edit
end
end
def user_params
return params.require(:user).permit(:username, :email)
end
def find_user
@user = User.find_by(id: params[:id])
render_404 unless @user
end
end
|
module NavigationHelpers
module Refinery
module Supports
def path_to(page_name)
case page_name
when /the list of supports/
admin_supports_path
when /the new support form/
new_admin_support_path
else
nil
end
end
end
end
end
|
# frozen_string_literal: true
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
can :read, :all
if user.is? :admin
can :manage, :all
elsif user.is? :user
can :read, User, user_id: user.id
cannot :read, Requirement
can :manage, Availability, user_id: user.id
can :manage, TeamsApplication, user_id: user.id
can :read, Schedule, user_id: user.id
can :read, Event
can :read, Shift
can :read, Team
else
can :read, Event
end
end
end
|
class CreateAuths < ActiveRecord::Migration
def change
create_table :auths do |t|
t.string :oauth_token
t.string :oauth_secret
t.integer :user_id
t.string :provider
t.string :dc
t.string :list_id
t.string :name
t.string :provider_id
t.timestamps
end
end
end
|
module Zergio
class ObjectBase
# Attributes shared by all objects.
attr_writer :id, :created_at, :updated_at
def id
if valid_id?
@id
else
@id = (@id.to_s.scan(/^(\d+)$/).first.first rescue nil)
end
end
def as_time(input)
input.kind_of?(Time) ? input : DateTime.parse(input.to_s).to_time
end
def created_at
as_time(@created_at)
end
def updated_at
as_time(@created_at)
end
def set_connection(conn)
@connection = (conn.respond_to?(:spawn)) ? conn : nil
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.