text stringlengths 10 2.61M |
|---|
require "grape-swagger"
class API < Grape::API
format :json
prefix :api
version 'v1', using: :path
rescue_from ActiveRecord::RecordNotFound do |e|
Rack::Response.new({ message: e.message }, 404).finish
end
mount V1::Stores
add_swagger_documentation mount_path: 'doc', api_version: 'v1'
end
|
require 'pry'
class Cell
class InvalidArgumentError < StandardError; end
def initialize(value)
validate_input(value)
@value = value
@potential_values = Array(1..9) unless @value
end
def solved?
value.is_a? Integer
end
def value
@value || @potential_values
end
def solve_for_value... |
require 'rails'
module Mist
class Engine < Rails::Engine
engine_name 'mist'
isolate_namespace Mist
initializer "mist.assets" do |app|
app.config.assets.precompile += ['mist_core.js', 'mist_core.css', 'mist.js', 'mist.css']
end
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper')
describe "/admin/tags/show" do
include Admin::TagsHelper
before(:each) do
@blog = mock_model(Blog, :title => 'Blog Title')
@tag = mock_model(Post)
@tag.stub!(:name).and_return("MyString")
@tag.stub!(:taggings).and_retu... |
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_filter :cors_preflight_check
after_filter :cors_set_access_control_headers
before_action :configure_permitted_parameters, :if => :devise_controller?
# Returns a datetime object from specified key in param... |
require 'inline'
class CPrimes < Primes
def self.prime?(number)
result = CExtension.new.is_prime(number)
result == 1
end
private
class CExtension
inline do |builder|
builder.include '<math.h>'
builder.c '
static int is_prime(long number) {
if (number < 2) {
... |
class AddSlabIdToInstantFeeDetails < ActiveRecord::Migration
def self.up
add_column :instant_fee_details, :slab_id, :integer
end
def self.down
remove_column :instant_fee_details, :slab_id
end
end
|
module UserVotable
extend ActiveSupport::Concern
included do
has_many :votes, dependent: :destroy
def vote_for(votable, value)
vote = self.votes.new(votable: votable, value: value)
vote.save
end
def unvote_for(votable)
self.votes.where(votable: votable).delete_all
end
... |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
#devise :registerable, :trackable, :omniauthable
# Setup accessible (or protected) attributes for your model
has_many :boards
has_many... |
class OffersController < ApplicationController
before_action :find_offer, only: [:show, :edit, :update, :destroy]
def index
@offers = Offer.limit(3).order("created_at DESC")
@search = Offer.search(params[:q])
end
def search
@search = Offer.search(params[:q])
@offerResults = @search.result.where("date > ?"... |
# frozen_string_literal: true
require 'jiji/test/test_configuration'
describe Jiji::Model::Logging::LogData do
include_context 'use data_builder'
it 'LogDataを作成してログを保存できる' do
data = Jiji::Model::Logging::LogData.create(Time.at(100))
expect(data.backtest_id).to be nil
expect(data.size).to eq 0
ex... |
class AboutController < ApplicationController
def index
@contacttitle = 'Church Contact Information: '
@contactperson = 'Contact Person: '
@contactnumber = 'Contact Number: '
@emailaddress = 'Email Address: '
@churchaddress = 'Our Church Address: '
@abouts = About.all
end
end
|
class CreateCityGlobalLocations < ActiveRecord::Migration
def self.up
create_table :city_global_locations do |t|
t.string :country
t.string :city
t.string :accent_city
t.integer :population
t.decimal :latitude, :precision => 12, :scale => 9, :default => 0
t.decimal :longitude, ... |
require 'pry'
class GossipsController < ApplicationController
before_action :check_login, only: [:create]
def new
@gossip = Gossip.new
end
def create
@gossip = Gossip.create('user_id' => session[:user_id], 'title' => params[:title], 'content' => params[:content])
puts @gossip.errors.messages
... |
class ListsController < ApplicationController
before_filter :find_list, :except => [:index, :new]
def index
@lists = List.all
end
def new
@list = List.new
end
def create
if @list.save
flash[:notice] = 'Success!'
redirect_to lists_url
else
flash[:error] = @list.errors.ful... |
require_relative '../../../../spec_helper'
describe 'icinga::plugin', :type => :define do
let(:title) { 'bear.sh' }
let(:params) { {:content => 'bear content'} }
it do
is_expected.to contain_file('/usr/lib/nagios/plugins/bear.sh')
.with_content('bear content')
.with_mode('0755')
end
end
|
class Ownership < Tag
validates :name, presence: true, uniqueness: true
has_many :vendor_ownerships
has_many :vendors, through: :vendor_ownerships
end
|
require_relative './user_interface'
require_relative './rubagotchi'
class GameManager
attr_accessor :user_interface, :rubagotchi
def initialize(user_interface = UserInterface.new, rubagotchi = nil)
@user_interface = user_interface
@rubagotchi = rubagotchi
end
def go_to_main_menu(user_input = nil)
... |
class Stock < ActiveRecord::Base
before_create :add_firebase_id
has_many :transactions
def add_firebase_id
firebase_object = firebase_base_client.push("stocks", {
symbol: self.symbol,
name: self.name
})
self.firebase_id = firebase_object.body["name"]
end
private
def firebase_base_... |
# frozen_string_literal: true
module Redox
module Models
class Destination < Redox::Model
redox_property :ID
redox_property :Name
end
end
end
|
# Aufgabe 1
# Erzeugen Sie ein Array beliebiger (von der Konsole vorgegebener) Länge
# und füllen Sie es mit Zufallszahlen zwischen 0 und 1.
@my_array = []
puts "Moin. Gib bitte die Laenge des Arrays ein:"
@length = gets
(0..@length.to_i).each { @my_array << rand }
# 1. geben Sie das Array aus
puts "\nInhalt des Arr... |
class User
class FavoriteSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes :id, :created_at, :updated_at, :links
def links
{
self: favorite_partner_users_path,
my_partners: my_partners_users_path
}
end
end
end
|
require 'rubygems'
require 'bundler'
Bundler.setup
require 'sinatra'
require 'nokogiri'
require 'open-uri'
require 'json'
configure do
# set user id (you can get yours here: http://www.idfromuser.com/)
user = '552273'
# feed url
url = "https://twitter.com/statuses/user_timeline/#{user}.rss/"
# get the... |
require_relative 'db_connection'
require 'active_support/inflector'
class SQLObject
def self.columns #execute2 takes a second argument like an array of strings, but it also interpolates
@columns ||= DBConnection.execute2("SELECT * from #{table_name}").first.map(&:to_sym)
@columns
end
def self.finalize!
... |
class AddTimerColumnToTests < ActiveRecord::Migration[6.1]
def change
add_column :tests, :minutes_for_passing, :integer, default: 10
end
end
|
class CONSTANTS
MAX_BOOKS_TO_BE_ISSUED = 5
MAX_LENDING_DAYS = 10
end
class RESERVATION_STATUS
OPEN, AVAILABLE, COMPLETED, CANCLED = 1, 2, 3, 4
end
class LENDING_STATUS
ACTIVE, RETURNED, RENEWED, DUE = 1,2,3,4
end |
class QuestionInputsController < ApplicationController
before_action :set_question_input, only: [:show, :edit, :update, :destroy]
# GET /question_inputs
# GET /question_inputs.json
def index
@question_inputs = QuestionInput.all
end
# GET /question_inputs/1
# GET /question_inputs/1.json
def show
... |
Then(/^I should see a button for ([^\"]*)$/) do |site|
link_id = '#' + site.downcase + '_snbutton'
expect(page.has_css?(link_id)).to be true
end
Then(/^I should not see a button for ([^\"]*)$/) do |site|
link_id = '#' + site.downcase + '_snbutton'
expect(page.has_css?(link_id)).to be false
end
Then(/^I should... |
class AddColumnToStudents < ActiveRecord::Migration
def change
add_column :students, :batch_type, :string
end
end
|
require 'spec_helper'
describe Comment, "About WineDetail Comment" do
let(:user) { Factory(:user) }
# let(:wine_detail) { Factory(:wine_detail)}
before(:each) do
@wine_detail = create(:wine_detail)
@comment = Comment.build_from @wine_detail, user.id, "Comment content"
end
it "comemnts_count should be... |
#case_statement.rb
#a = 7
#case a
#when 5
#when 6
# puts "a is 6"
#else
# puts "a is neither 5, nor 6"
#end
# case_statement.rb <-- refactored
#a = 5
#answer = case a
#when 5
# "a is 5"
#when 6
# "a is 6"
#else
# "a is neither 5, nor 6"
#end
... |
class SessionsController < ApplicationController
# GET /admin_login
def new
return unless current_admin
redirect_to root_path
end
# GET /admin_logout
def delete
log_out
redirect_to root_path
end
# POST /admin_login
def create
admin = Admin.find_by(login: params[:formSession][:l... |
require 'rails_helper'
RSpec.describe Ip, type: :model do
it 'ip is valid' do
ip = Ip.new(address: '192.168.15.1')
expect(ip).to be_valid
end
it 'ip is not valid, address is not a ip address' do
ip = Ip.new(address: '124.5454.1215.2')
expect(ip).to_not be_valid
end
it 'ip is not valid, ip i... |
module SmsMock
class Message
attr_accessor :to, :body, :from
def initialize(opts = {})
@to = opts[:to]
@body = opts[:body]
@from = opts[:from]
end
end
end |
class MatchesController < ApplicationController
def show
render json: MatchSerializer.new(match).to_detailed_serialized_json
end
def create
@match = Matches.create(match_params)
end
def match
Matches.find(params[:id])
end
def match_params
params.require(:ma... |
class Volunteer < ActiveRecord::Base
belongs_to :congregation
belongs_to :responsibility
has_one :vacancy
scope :by_congregation_id, -> congregation_id { where("congregation_id = ?", congregation_id) }
scope :without_vacancies, -> { where("id not in (?)", Vacancy.where("volunteer_id is not null").pluck(:volu... |
FactoryGirl.define do
factory :state do
name {Faker::Address.state}
acronym {Faker::Address.state_abbr}
end
end
|
# == Informacion de la tabla
#
# Nombre de la tabla: *dbm_enlace_urls*
#
# id :integer(11) not null, primary key
# nombre :string(255)
# descripcion :string(255)
# url :string(255)
# orden :integer(11)
# created_at :datetime
# updated_at :datetime
# imagen :string(255)
# ... |
class UsersController < ApplicationController
before_action :set_user, except: [:index, :new, :create]
before_action :authenticate_user, except: [:index, :show, :new, :create]
# GET /users
# GET /users.json
def index
@users = User.all
end
# GET /users/1
# GET /users/1.json
def show
@shops = ... |
#TEDDIT: Strings - Student's File
# Teddit is a Ruby text based news aggregator. Think Reddit in your terminal.
# This exercise will be used throughout the ruby portion of this course.
# We will incrementally build a news aggregator (next week using API's)
# We will create a more dynamic Teddit, and pull the latest ne... |
require 'test_helper'
class LicenseTest < ActiveSupport::TestCase
def setup
@by = License.find('by')
@public = License.find('public')
@copyleft = License.find('copyleft')
@sample = License.find('cc-sample')
end
test "finds by id and short_name" do
assert License.find('by').present?
asser... |
#!/usr/bin/env ruby
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'password_generator'
require 'optparse'
options = {}
option_parser = OptionParser.new do |opts|
executable_name = File.basename($PROGRAM_NAME)
opts.banner = "Usage: #{executable_name} [options] length"
options[:file] = '.p... |
# Manage the conversion of hashes and string to json
module ResponseBuilder
def self.parse_file(filename)
base_path = File.dirname(__FILE__)
path = "#{base_path}/../json_templates/#{filename}.json"
file = File.read(path)
@template = JSON.parse(file)
@copy = @template.is_a?(Hash) ? Hash[@template] ... |
json.goal_entries do
json.partial! 'api/v1/goal_entries/show', collection: @goal_entries, as: :goal_entry
end
|
FactoryBot.define do
factory :phone_number, class: PhoneNumber do
number_type "telephone"
tel_number "0117 900 1000"
start_date Time.zone.now
end_date Time.zone.now
end
end
|
class User < ApplicationRecord
has_many :groups
has_many :gifts
validates :name, presence: true, uniqueness: true, length: { minimum: 3, maximum: 24 }
end
|
require 'test_helper'
class ErrorSerializerTest < Minitest::Spec
class Problem < TestModel
attr_accessor :id, :name, :number, :date
end
class DefaultsSerializer < SimpleJsonapi::ErrorSerializer
end
class BlocksSerializer < SimpleJsonapi::ErrorSerializer
id(&:id)
status { "422" }
code(&:numb... |
# The check digit for ISBN-13 is calculated by multiplying each digit
# alternately by 1 or 3 (i.e., 1 x 1st digit, 3 x 2nd digit,
# 1 x 3rd digit, 3 x 4th digit, etc.), summing these products together,
# taking modulo 10 of the result and subtracting value from 10,
# and then taking the modulo 10 of the result aga... |
require 'tzinfo'
class Weather
attr_reader :lat_long,
:summary,
:details
def initialize(location, lat_long, google_location_info, current_forecast, evening_forecast)
@location = location
# @location_info = google_location_info
@lat_long = lat_long
# @current_full_foreca... |
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_action :authorize, only: [:index, :show]
def index
@users = User.all
end
def show
@signups = Signup.all.where(user_id: @user.id)
@campaigns = Campaign.all
@e... |
class Download < ActiveJob::Base
queue_as :default
after_perform :convert
attr_reader :url
def perform(url)
@url = url
FileUtils.mkdir_p(File.dirname(path))
File.open(path, 'wb') { |fp| fp.write(faraday.body) }
end
private
def convert
Convert.perform_later(path.to_s)
end
def fara... |
require 'util'
#
# USAGE: [environment=production] [limit=10000] [rate=500] bundle exec rails runner script/upload_assets.rb /path/to/photos
#
HOST = ENV['environment'] == 'production' ? 'www.kafki.com' : 'vm.kafki.com:3000'
limit = (ENV['limit'] || 10000).to_i
rate_limit = (ENV['rate'] || 500).to_i
types = Asset.fi... |
# t.string 'title', null: false
# t.bigint 'teacher_id', null: false
class Course < ApplicationRecord
belongs_to :teacher, class_name: 'User', foreign_key: 'teacher_id', dependent: :destroy
has_many :course_sessions, dependent: :nullify
has_many :session_attendees, through: :course_sessions, dependent: :nullify... |
# frozen_string_literal: true
module Tar
class Schema
def initialize(&block)
@fields = {}
@offset = 0
instance_eval(&block)
@fields.freeze
@unpack_format = @fields.values.map(&:unpack_format).join.freeze
end
def field_names
@fields.keys
end
def clear(record,... |
class PagesController < ApplicationController
def dashboard
unless current_player
redirect_to player_session_path
end
@games_to_confirm = current_player.games_to_confirm
@pending_games = current_player.pending_games
@recent_games = Game.all.where(confirmed: true).order("created_at DESC").l... |
module Praxis
module Responses
class ValidationError < BadRequest
def initialize(errors: nil, exception: nil, message: nil, **opts)
super(**opts)
@headers['Content-Type'] = 'application/json' #TODO: might want an error mediatype
@errors = errors
@exception = exception
... |
class Api::ModelsController < Api::ApiController
expose :models, -> { params[:category] ? @active_company.models.find_by_category(params[:category]) : @active_company.models }
expose :model, id: ->{ params[:slug] }, scope: ->{ @active_company.models.includes_associated }, model: Model, find_by: :slug
# GET api/m... |
#Fedena
#Copyright 2011 Foradian Technologies Private Limited
#
#This product includes software developed at
#Project Fedena - http://www.projectfedena.org/
#
#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 ... |
class LinkedAccountsController < ApplicationController
# DELETE /links/1
# DELETE /links/1.json
def destroy
@linked_account = current_user.linked_accounts.find(:first, :conditions => ["provider = ?", LinkedAccount::PROVIDERS[params[:provider].to_sym]])
@linked_account.try(:destroy)
respond_to do |f... |
class AddTelegramReferenceToCustomers < ActiveRecord::Migration[6.0]
def change
add_column :customers, :telegram_reference, :string
Customer.find_each do |customer|
customer.update(telegram_reference: customer.telegram_id)
end
end
end
|
#string
#pueden ser con "" o ''
=begin
"".methods lista todos los metodos que se pueden utilizar en una cadena de string
=end
# encoding: UTF-8
puts "León, Corazón"
#\n realiza un enter, si se coloca sin puts la cadena lo imprime como parte del texto
#\t es una tabulacion otra forma de conservar eso como te... |
# # initial solution
# def digit_list num
# num_list = []
# if num >= 0
# while num > 10
# tmp = num % 10
# num_list << tmp
# num -= tmp
# num /= 10
# end
# if num > 0 then num_list << num end
# return num_list.reverse
# end
# end
# second solution
def digit_list num
... |
require 'digest'
module Runa
class QueuedJob
class DeserializationError < StandardError; end
## A hash of all attributes related to this job
attr_accessor :attributes
## Construct a new QueuedJob based on the attributed hash provided.
def initialize(attributes = {})
@attribut... |
class Book < ApplicationRecord
scope :contains, -> (search) { where("author like ? or name like ?", "%#{search}%", "%#{search}%")}
end
|
class Cluster < ActiveRecord::Base
belongs_to :user
has_many :links, dependent: :destroy
validates :user_id, presence: true
validates :name, presence: true
end
|
require_relative '../src/direction'
describe 'Direction' do
describe ',turnRight' do
it 'should return E when given N and turn right' do
direction = Direction.new('N')
expect(direction.turnRight).to eq('E')
end
it 'should return N when given E and turn right' do
direction = Direction.n... |
class LikesController < ApplicationController
before_action :authenticate_user!, only: [:toggle]
before_action :likeable_exists!
def fetch
@likes = Like.where(shared_params).includes(profile: :avatar)
render action: 'fetch', layout: false if request.xhr?
# respond_with decorate likes_enriched
end
... |
# -*- encoding : utf-8 -*-
class CreateDonations < ActiveRecord::Migration
def change
create_table :donations do |t|
t.integer :artist_id
t.decimal :artist_percentage
t.decimal :stoffi_percentage
t.decimal :charity_percentage
t.decimal :amount
t.integer :user_id
t.timest... |
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "horai"
s.version = "0.6.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_v... |
require 'spec_helper'
describe BookingsController do
let!(:user) { FactoryGirl.create(:confirmed_user) }
let!(:club_night) { user.club_nights.create(FactoryGirl.attributes_for(:club_night)) }
let!(:event) { club_night.events.create(FactoryGirl.attributes_for(:event)) }
let!(:time_slot) { FactoryGirl.create(:ti... |
require "spec_helper"
RSpec.describe "Day 14: Disk Defragmentation" do
let(:runner) { Runner.new("2017/14") }
let(:input) { "flqrgnkx" }
describe "Part One" do
let(:solution) { runner.execute!(input, part: 1) }
it "computes the number of used spaces across a 128x128 grid" do
expect(solution).to e... |
# Implementar en este fichero la clase para crear objetos racionales
# Author: Juan Francisco Chávez González
# Practica 5 LPP
require "./gcd.rb"
class Fraccion
# método inicializar clase
def initialize(n, d)
# atributos
max = gcd(n,d) #maximo comun divisor
@n = n / max #reducida a su mínima expresi... |
class AddIndexToReceiptNumberSetOnName < ActiveRecord::Migration
def self.up
add_index :receipt_number_sets, [:name], :name => "index_by_name"
end
def self.down
remove_index :receipt_number_sets, :name => "index_by_name"
end
end
|
require 'csv'
class PersonParser
attr_reader :file
def initialize(file)
@file = file
end
def people
# In this method we're going to return
# the value of the instance variable @people.
# However, before returning the value, we might have to first
# calculate the value and assign it to the... |
class BeefsController < ApplicationController
before_action :set_beef, only: [:show, :edit, :update, :destroy]
# GET /beefs
# GET /beefs.json
def index
@beefs = Beef.all
end
# GET /beefs/1
# GET /beefs/1.json
def show
end
# GET /beefs/new
def new
@beef = Beef.new
end
# GET /beefs/1... |
require 'rails_helper'
RSpec.describe ApplicationController do
describe '#ensure_user_signed_in' do
controller do
before_action :ensure_user_signed_in
def index
render inline: 'hello'
end
end
it 'allows signed in users to access' do
session[:auth_id] = 'auth0|123456789'
... |
Gem::Specification.new do |s|
s.name = 'opportune'
s.version = '0.0.0'
s.date = '2011-03-06'
s.summary = "optimal decisions amidst uncertainty"
s.description = "holder for decision logic"
s.authors = ["Ben Doyle"]
s.email = 'doyle.ben@gmail.com'
s.files = ["lib/oppo... |
require 'twine_test'
class PlaceholderTest < TwineTest
def assert_starts_with(prefix, value)
msg = message(nil) { "Expected #{mu_pp(value)} to start with #{mu_pp(prefix)}" }
assert value.start_with?(prefix), msg
end
def placeholder(type = nil)
# %[parameter][flags][width][.precision][length]type (se... |
class RenameRecipientsDeskId < ActiveRecord::Migration
def change
rename_column :recipients, :desk_id, :workstation_id
end
end
|
class Life
def initialize(field)
@field = field
end
def step!
new_grid = @field.make_grid
@field.grid.each_with_index do |row, y|
row.each_with_index do |cell, x|
count = lives_counter(y,x)
new_grid[y][x] = if cell.zero?
Game::Rules::NEW_ONE.include?(count) ? 1 : 0
... |
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_attached_file :avatar,
styles:... |
require 'rails_helper'
RSpec.describe FacilitiesManagement::Lot, type: :model do
subject(:lots) { described_class.all }
let(:first_lot) { lots.first }
let(:all_numbers) { described_class.all_numbers }
it 'loads lots from CSV' do
expect(lots.count).to eq(3)
end
it 'populates attributes of first lot' ... |
require 'open-uri'
require 'net/http'
class Notification < ApplicationRecord
belongs_to :user
after_save :upload_notification_to_ionic
validates :message, presence: true
validates :tokens, presence: true
private
def upload_notification_to_ionic
puts "Push Notification Created: Sent-to: self.tokens.to_... |
require("rspec")
require("parcel.rb")
describe("Parcel") do
it("the total volume of the package is < 30, the base price to ship it is 5") do
test_package = Parcel.new(2,3,4,40,0,0,"true")
expect(test_package.volume()).to(eq(5))
end
it("the total volume of the package between 30 and 100, the base price to... |
require 'spec_helper'
module PriorityTest::Core
describe Configuration do
let(:config) { Configuration.new }
describe "#add_setting" do
context "with no additional options" do
before { config.add_setting :custom_option }
it "defaults to nil" do
config.custom_option.should be... |
module Kaseya::VSA
class VSAError < Kaseya::ApiError
attr_reader :response, :code, :error
def initialize(response)
@response = response
if @response&.body
@code = @response.body["ResponseCode"]
@error = @response.body["Error"]
end
super("Error (#{@code}): #{@error || ... |
module TweetReviewsHelper
def rating_options
Rating::SCORES.to_a.inject('-- Choose Rating --' => nil) do |ratings, rating|
ratings.merge("#{Rating::DESCRIPTIONS[rating.last]} (#{rating.first})" => rating.last)
end
end
def rating_group_links
Rating::SCORE_GROUPS.inject([]) do |links, (group, des... |
require 'fileutils'
class ModuleController < ApplicationController
before_filter :authorize, :only => [:update, :add_revision, :edit, :update_revision]
def new
@sidebar="sidebar_index"
@package = Package.new
@keywords = Keyword.find(:all)
@author = Author.find(session[:uid])
end
def create
... |
module Slugifymodule
module SlugMethod
def slug
name.downcase.tr(' ', '-')
end
end
module FindbySlugMethod
def find_by_slug(slug)
self.all.detect do |item|
item.slug == slug
end
end
end
end
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "TaskResponse" do
describe ".create_collection_from_array" do
it "should create responses from an array" do
r = SharedWorkforce::TaskResponse.create_collection_from_array([{'answer'=>'answer 1'}, {'answer'=>'answer 2'}])
r[0].... |
json.array!(@item_groups) do |item_group|
json.extract! item_group, :id, :item_group_name
json.url item_group_url(item_group, format: :json)
end
|
class LineAuthService
def initialize(api_uri)
@api_uri = api_uri
end
def execute(body)
nonce = SecureRandom.uuid + Time.now.to_i.to_s
resp = Faraday.post("#{ENV['line_pay_server']}#{@api_uri}") do |req|
req.headers['Content-Type'] = 'application/json'
req.headers['X-LINE-ChannelId'] = ENV... |
class BooksController < ApplicationController
before_action :set_book, only: [:show, :edit, :update, :destroy, :rent, :return]
# GET /books
# GET /books.json
def index
@books_rented = Book.joins("JOIN rent_logs ON books.id = rent_logs.book_id AND rent_logs.return_at IS NULL")
@books_available = Bo... |
class Matching < ActiveRecord::Base
has_many :engagements
serialize :projects, Array
serialize :preferences, Hash
serialize :result, Hash
serialize :last_edit_users, Hash
@@STATUSES = ['Collecting responses', 'Responses collected', 'Completed']
validates_presence_of :name, :projects, messa... |
james_harrison = PlayerCard.create do |card|
card.first_name = 'James'
card.last_name = 'Harrison'
card.overall = 97
card.team_chemistry_id = Chemistry.by_team_city(:pittsburgh).first.id
card.program = NFL_REPLAYS
card.position ... |
require 'pg'
require 'date'
def log_and_update_message(level, msg, update_message=false)
$evm.log(level, "#{msg}")
@task.message = msg if @task && (update_message || level == 'error')
end
def encode_slash(string)
encoded_string = string.gsub("/","%2f")
return encoded_string
end
def parse_hash(hash, options_h... |
require 'minicomic-backend/output_filter'
require 'minicomic-backend/image_processing'
require 'fileutils'
#
# Process an input file for the Web
#
class TempBitmapToWeb < OutputFilter
include ImageProcessing
def build(input, output)
FileUtils.mkdir_p(File.split(output).first)
quality = @config['quality'] ... |
class RenamePresentationToDocumentTasks < ActiveRecord::Migration
def change
rename_table :learning_dynamics_to_document_tasks, :learning_dynamic_to_document_tasks
end
end
|
class DefaultAnswer < ActiveRecord::Migration
def change
change_column :answers, :like_counter, :integer,default: 0
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
after_filter :set_csrf_cookie_for_ng
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def set_csrf_cookie_for_ng
cookies['XSRF-TOKEN'] = form_authenticity_token if protect_again... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.