text stringlengths 10 2.61M |
|---|
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/trusty64"
config.vm.network "private_network", type:"dhcp"
end
|
module Celluloid
# A proxy which creates future calls to an actor
class FutureProxy < AbstractProxy
attr_reader :mailbox
# Used for reflecting on proxy objects themselves
def __class__; FutureProxy; end
def initialize(mailbox, klass)
@mailbox, @klass = mailbox, klass
end
def inspect... |
# -*- coding : utf-8 -*-
module Mushikago
module Hanamgri
class GetListDomainsRequest < Mushikago::Http::GetRequest
def path; "/1/hanamgri/domains" end
request_parameter :limit
request_parameter :offset
request_parameter :filter
def initialize options={}
super(options)
... |
namespace :mail do
desc "Sending daily email to admin"
task daily_mail: :environment do
DailyMailer.dailymail.deliver_now
end
end
|
# 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 = %q{pcapr-local}
s.version = "0.1.13"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_r... |
# == Schema Information
#
# Table name: comments
#
# id :bigint not null, primary key
# content :string
# created_at :datetime not null
# updated_at :datetime not null
# commenter_id :integer
# post_id :integer
#
# Indexes
#
# index_comments_on_commenter_id (com... |
class Log < ApplicationRecord
belongs_to :item
has_many :comments , dependent: :destroy
attachment :image
validates :item_id, presence: true
validates :title, presence: true
validates :body, presence: true
validates :from, presence:true
# validates :status, presence: true
enum fro... |
#####################################################
# t_workbook.rb
#
# Test suite for the Workbook class (workbook.rb)
# Requires testunit 0.1.8 or greater to run properly
#####################################################
base = File.basename(Dir.pwd)
if base == "test" || base =~ /spreadsheet/i
Dir.chdir("..... |
class OrgaSerializer
include FastJsonapi::ObjectSerializer
set_type :orgas
attributes :title, :created_at, :updated_at, :active
attribute :title
attribute :created_at, if: Proc.new { |record, params| params.blank? || !params[:public] == true }
attribute :updated_at, if: Proc.new { |record, params| params.b... |
class FixStoreModel < ActiveRecord::Migration[5.1]
def change
remove_column :stores, :store_hash, :string
add_column :stores, :store_hash, :jsonb, default: '{}', null: false
remove_column :stores, :email, :string
remove_column :stores, :username, :string
end
end
|
# frozen_string_literal: true
require_relative '../helpers/spec_helper'
require_relative '../helpers/vcr_helper'
require_relative '../helpers/database_helper'
require 'rack/test'
def app
IndieLand::App
end
# rubocop:disable Metrics/BlockLength
describe 'Test API routes' do
include Rack::Test::Methods
VcrHelpe... |
class AddRoleOtherToImpSurveys < ActiveRecord::Migration
def change
add_column :imp_surveys, :role_other, :boolean
end
end
|
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@bitches = Bitch.where(user_id: [@user.id]).page(params[:page]).per(12)
end
end
|
module Taobao
class Shop < Model
def self.attr_names
[:sid, :cid, :nick, :title, :desc, :bulletin, :pic_path, :created, :modified, :shop_score]
end
attr_names.each do |attr_name|
attr_accessor attr_name
end
end
end
|
class ProductsController < ApplicationController
before_action :is_authenticated?
before_action :get_product, except: [ :index, :new, :create ]
def new
@product = Product.new
end
def create
@product = Product.new ( product_params )
if @product.save
redirect_to gear_form_url ( @product )
... |
require 'spec_helper'
describe GymsController do
describe '#index' do
let!(:akihabara) { create(:gym, :name => 'Akihabara B-PUMP') }
let!(:ogikubo) { create(:gym, :name => 'Ogikubo B-PUMP') }
let!(:shelter) { create(:gym, :name => 'Shelter') }
context 'with query' do
before { get :index, :quer... |
require 'test_helper'
class HistoricsControllerTest < ActionDispatch::IntegrationTest
setup do
@historic = historics(:one)
end
test "should get index" do
get historics_url
assert_response :success
end
test "should get new" do
get new_historic_url
assert_response :success
end
test "... |
class ProductPrompt < ActiveRecord::Base
####
# CONSTANTS
####
VALUE_MAX_LENGTH = 255
acts_as_list :scope => ['cobrand_id = #{self.cobrand_id.to_s} AND interest_id = #{self.interest_id}']
####
# RELATIONSHIPS
####
belongs_to :interest
belongs_to :category
belongs_to :cobrand
has_ma... |
class DataTable
def header=( header )
raise InvalidHeader unless header.is_a?( Array ) && header.size > 0
header.each { |name| raise InvalidHeaderColumn unless name.is_a?( String ) }
@header = header
end
private
def valid_header?
!@header.empty?
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Install dependencies
$install = <<SCRIPT
add-apt-repository ppa:agent-8131/ppa
apt-get update -qq
apt-get -y install cmake make gcc g++ flex bison libpcap-dev libssl-dev python-dev swig zlib1g-dev libmagic-dev
apt-get -y install tcpreplay
SCRIPT
# libgoogle-perftools-dev
$ke... |
class ReservationValidationEmailWorker
include Sidekiq::Worker
def perform(booking_name, restaurant_name)
#get restaurant emails
emails = Restaurant.find_by(name: restaurant_name).emails
#split emails into array
emailArray = emails.split(' ')
#send to admin also
emailArray << ENV["ADMIN_EMAI... |
class CommentsController < ApplicationController
before_action :set_comment, only: [:show, :update, :edit, :destroy]
# GET /comments
# GET /comments.json
def index
@comments = Comment.all
end
# GET /comments/1
# GET /comments/1.json
def show
end
# GET /comments/new
def new
@comment = Co... |
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.integer :walter_id, null: true
t.integer :intranet_id, null: true
t.string :email, null: false
t.string :password_digest, null: false
t.string :first_name, null: false
t.string :last_name, ... |
class Album < ApplicationRecord
has_many_attached :images
# アルバムの最古年度から最新年度の範囲演算子を取得
def self.get_album_period
self.get_first_year..self.get_last_year
end
# 指定年のアルバムを取得
def self.get_lab_albums(lab_id, year='')
if year.empty?
where(lab_id: lab_id)
else
where(lab_id: lab_id).where(cre... |
class CreateSkills < ActiveRecord::Migration
def change
create_table :skills do |t|
t.string :title
# time
t.timestamps
end
execute <<-SQL
CREATE INDEX ix_skills_lower_title ON skills(lower(title) varchar_pattern_ops);
SQL
end
end
|
#!/usr/bin/env ruby
class GitDiff
attr_reader :filenames
def initialize
@filenames = `git diff --cached --name-only --diff-filter=ACM`.split("\n")
end
end
class Check
attr_reader :diff, :exit_status, :files
def initialize(diff)
@diff = diff
end
def check
before_run
puts "Running \033[... |
module Vuf
class Server
def initialize(port, session_klass)
@port = port
@sessions_ctx = {}
@server_thread = nil
@closing_q = Queue.new
@session_klass = session_klass
@wp = Vuf::WorkingPool.new(4)
@wp.run
end
def start
if @server_thread.n... |
class TransactionsController < ApplicationController
before_filter :authorize
before_action :set_transaction, only: [:edit, :update, :destroy]
helper_method :transactions_per_page_list
def transactions_per_page_list
[10, 20, 50]
end
def index
@per_page = params[:per_page].to_i > 0 ? params[:per_pa... |
# -*- ruby -*-
require 'tempfile'
task :default => :build
REVEAL_THEME = "moon"
PANDOC_HTML_OPTS = [
'-i',
'-V', "theme:#{REVEAL_THEME}",
'-t', 'revealjs',
'--smart'
]
PANDOC_PDF_OPTS = [
'-t', 'beamer',
'-V', 'theme:Warsaw',
'--template', 'pdf-template.tex'
]
task :build => [:html, :pdf]
task :htm... |
require 'open-uri'
class RTL
HTML_TAG = /<rtl-player(?:[^>]+hls=\"(.*?)\"[^>]*)?>/
HLS_MANIFEST = /(?:#EXT-X-STREAM-INF:)(?:BANDWIDTH=(?<BANDWIDTH>\d+),?|RESOLUTION=(?<RESOLUTION>\d+x\d+),?)*\n(?<FILE>[.\w]*)/m
TMP_FOLDER = 'tmp/'
def self.fetch(url)
URI.parse(url).read
end
def self.filename(url)
... |
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "crazy_harry/version"
Gem::Specification.new do |s|
s.name = "crazy_harry"
s.version = CrazyHarry::VERSION
s.authors = ["TA Tyree"]
s.email = ["todd.tyree@lonelyplanet.co.uk"]
s.homepage = "https://github.c... |
class Spiped < Formula
homepage "https://www.tarsnap.com/spiped.html"
url "https://www.tarsnap.com/spiped/spiped-1.5.0.tgz"
sha256 "b2f74b34fb62fd37d6e2bfc969a209c039b88847e853a49e91768dec625facd7"
bottle do
cellar :any
sha1 "dc03cb40b160fa0720b228fb54aafaff05425790" => :yosemite
sha1 "59ec8ccb0d50... |
require 'test_helper'
class PostTest < ActiveSupport::TestCase
def setup
@user = users(:taro)
@post = @user.build_post(title: "Hello", content: "This is test post")
end
test "should be valid" do #有効なポストかどうかの確認
@post = @user.build_post(title: "Hello", content: "This is test post", picture: "rails.pn... |
require 'test/unit'
require 'yaml'
class Collections_tests < Test::Unit::TestCase
# def setup
# end
# def teardown
# end
#System::Console.ReadLine()
def test_load_mapping_from_string
y = <<-EOF
dog: canine
cat: feline
badger: malign
EOF
foo = YAML::load(y)
assert(foo.size... |
# A very simple demonstration of writing a REST server
# for Simple RPC clients that takes requests over HTTP
# and returns results as JSON structures.
# Inspired with mcollective/ext/mc-rpc-restserver.rb demo
# in the MCollective source code
# Copyright (C) 2011 Marco Mornati (mornatim at gmail.com)
# Copyright (C) ... |
# frozen_string_literal: true
class AddCustomFieldToTeams < ActiveRecord::Migration[5.0]
def change
add_column :teams, :custom_field, :string
end
end
|
# Problem: Write a method that takes an array of numbers an Multiplies them,
# then divides them by arr length. Finally round to 3 decimal places
# Input: Array of Numbers
# Output: Float with 3 Decimals
# Steps:
# 1: Define a method and print out the original array
# 2: initialize a total variable = 0
# 2b:... |
class AffiliateContactList < ContactList
attr_accessor :sub_type
def contacts
return [] unless self.sub_type
User.where("affiliation_list LIKE '%#{self.sub_type}%'")
end
def display_name
if self.sub_type
"Affiliate - #{User.affiliation_types.select { |c| c[1] == self.sub_type }.first[0]}"
else
"Aff... |
# encoding: utf-8
control "V-92637" do
title "Expansion modules must be fully reviewed, tested, and signed before they can exist on a production Apache web server."
desc "In the case of a production web server, areas for content development and testing will not exist, as this type of content is only permissible on a... |
class Node
attr_accessor :val, :next_node
def initialize(val, next_node=nil)
@val = val
@next_node = next_node
end
end
class LinkedList
attr_accessor :head, :tail
def initialize(val)
new_node = Node.new(val, nil)
@head = new_node
@tail = new_node
end
def pretty
current = @head
out = ""
while... |
class RemoveCourseToQuestion < ActiveRecord::Migration
def change
remove_column :questions, :course_id, :integer
end
end
|
require "helper"
describe Bridge::Score do
before do
@score = Bridge::Score.new("1SN", "NONE", 9)
end
it "return made contract?" do
score = Bridge::Score.new("6SN", "NONE", 9)
refute score.made?
score = Bridge::Score.new("3NTN", "NONE", 3)
refute score.made?
score = Bridge::Score.new("7N... |
module Neo4j
module Shared
describe QueryFactory do
before do
stub_active_node_class('NodeClass') {}
stub_active_rel_class('RelClass') do
from_class false
to_class false
end
end
describe '.factory_for' do
subject { described_class.factory_for... |
require_relative 'inversion'
class InversionDolares < Inversion
class CotizacionesInvalidasError < StandardError
end
def initialize(monto, cotizacion_inicial, cotizacion_final)
super(monto)
if cotizacion_inicial <= 0 or cotizacion_final <= 0
raise CotizacionesInvalidasError
end
@cotizacio... |
# frozen_string_literal: true
class Test < ApplicationRecord
belongs_to :category
has_many :questions
has_many :test_passages
has_many :users, through: :test_passages
belongs_to :users, optional: true
validates :title, presence: true
validates_uniqueness_of :title, scope: :level
validates :level, nume... |
$LOAD_PATH.unshift(File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "ruby")))
require "grpc"
require "generic_services_pb"
def bin_to_hex(bin)
"0x#{bin.unpack1('H*')}"
end
def main
stub = Generic::GenericService::Stub.new("127.0.0.1:4000", :this_channel_is_insecure)
request = Generic::GenericPara... |
RSpec.describe "layouts/application" do
# standard:disable Lint/ConstantDefinitionInBlock
class ActionView::TestCase::TestController
include Auth
def current_user
nil
end
end
# standard:enable Lint/ConstantDefinitionInBlock
it "shows the meta tags when ROBOT_NOINDEX is set to true" do
... |
#!/usr/bin/env ruby
# https://adventofcode.com/2022/day/7
# --- Day 7: No Space Left On Device ---
# You can hear birds chirping and raindrops hitting leaves as the expedition proceeds. Occasionally, you can even hear much louder sounds in the distance; how big do the animals get out here, anyway?
# The device the E... |
require File.dirname(__FILE__) + '/../test_helper'
class RsvpTest < ActiveSupport::TestCase
context 'working with AR validations' do
def setup
@rsvp = Rsvp.new
@user = Factory.build :user, :first_name => nil, :last_name => nil, :email => nil
end
test 'should require first na... |
require 'spec_helper'
describe "manifests/new" do
before(:each) do
assign(:manifest, stub_model(Manifest,
:title => "MyString",
:text => "MyText",
:order => 1
).as_new_record)
end
it "renders new manifest form" do
render
# Run the generator again with the --webrat flag if you ... |
#
# Cookbook Name:: fail2ban
# Recipe:: default
#
# Dependency on iptables
include_recipe "iptables"
if ['solo', 'app', 'util', 'app_master', 'db_master', 'db_slave'].include?(node[:instance_role])
include_recipe "fail2ban::install"
include_recipe "fail2ban::config"
# Start the fail2ban service
service "fail2ban... |
module Amiando
##
# http://developers.amiando.com/index.php/REST_API_Addresses
class Addresses < Resource
##
# This request will return the billing address object of the user
# with the specified internal id. The response contains all
# properties marked with R. If there hasn't been at least on... |
FactoryGirl.define do
factory :market_hierarchy_result_hierarchy_node, class: IGMarkets::MarketHierarchyResult::HierarchyNode do
id '174882'
name 'Indices'
end
end
|
require 'rails_helper'
RSpec.describe Contact, type: :model do
it "nameがない場合は登録できないこと" do
contact = build(:contact, name: "")
contact.valid?
expect(contact.errors[:name]).to include("を入力してください")
end
it "emailがない場合は登録できないこと" do
contact = build(:contact, email: "")
contact.valid?
exp... |
require 'sequel'
require 'rspec/sequel_expectations'
require 'faker'
require 'pry'
require_relative '../db'
RSpec.configure do |config|
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printe... |
require "erb"
# Root ProjectRazor namespace
module ProjectRazor
module ModelTemplate
# Root Model object
# @abstract
class VMwareESXi < ProjectRazor::ModelTemplate::Base
include(ProjectRazor::Logging)
# Assigned image
attr_accessor :image_uuid
# Metadata
attr_accessor :hos... |
# encoding: UTF-8
#
# Cookbook Name:: postfixadmin
# Author:: Xabier de Zuazo (<xabier@zuazo.org>)
# Copyright:: Copyright (c) 2013-2015 Onddo Labs, SL.
# 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 L... |
RSpec.describe "home/partner_organisation" do
context "when there are no active reports" do
before do
assign(:current_user, build(:partner_organisation_user))
assign(:grouped_activities, [])
assign(:reports, nil)
allow(view).to receive(:organisation_reports_path).and_return("/reports/id")... |
class EasyPageZone < ActiveRecord::Base
self.table_name = 'easy_page_zones'
has_many :available_in_pages, :class_name => "EasyPageAvailableZone", :foreign_key => 'easy_page_zones_id'
validates_length_of :zone_name, :in => 1..50, :allow_nil => false
before_save :change_zone_name
@@easy_page_zones = {}
E... |
module Monkeyshines
module Fetcher
FakeResponse = Struct.new(:code, :message, :body)
class FakeFetcher < Base
# Fake a satisfied scrape_request
def get scrape_request
response = FakeResponse.new('200', 'OK', { :fetched => scrape_request.url }.to_json )
scrape_request.response_cod... |
class FilmsController < ApplicationController
def index
@films = Film.all
end
def show
@film = Film.find(params[:id])
end
def new
@film = Film.new
end
def edit
@film = Film.find(params[:id])
end
def create
found = false
@film = Film.new(film_params)
Film.all.ea... |
# Finds our images from partial filenames
require 'find'
# Number of potential hits returned in the list of matches
NUM_MATCHES = 8
# Holds logic to process pass an uploaded CSV file to the CSV Importer.
# Loads a reference to a virtual ORM model that can be used to manipulate the imported data.
class Job
# This e... |
require 'pp'
class AssertionError < StandardError
end
class TestResult
def initialize
@run_count = 0
@errors = []
end
def test_started
@run_count += 1
end
def test_failed(name)
@errors << { name: name }
end
def fail_count
@errors.count
end
def summary
"#{@run_count} run, ... |
class NewRoman
public
def generator number
remainder = number
roman_string = ''
until remainder == 0
if remainder >= 4000 # break out of loop
remainder = 0
return 'error'
elsif remainder >= 1000 #&& remainder < 4000
roman_string += 'M'
rem... |
# frozen_string_literal: true
RSpec.describe Dry::Types::Nominal do
describe "params.nil" do
subject(:type) { Dry::Types["params.nil"] }
it_behaves_like "a constrained type", inputs: [Object.new, %w[foo]]
it "coerces empty string to nil" do
expect(type[""]).to be(nil)
end
end
describe "p... |
class RemoveEndTimeFromBookings < ActiveRecord::Migration[5.0]
def change
remove_column :bookings, :end_time, :time
end
end
|
class AddUniqueIndexToHairdata < ActiveRecord::Migration
def change
add_index :hairdata, [:userid,:timedate], unique: true
end
end
|
# encoding: utf-8
require "find"
module Generetta
ClassModel = Struct.new(:classname,:methods)
MethodModel = Struct.new(:name,:context)
module Parser
def self.find_files
dir = "#{Rails.root.to_path}/app/models"
# 読み込み可能なファイル一覧
readable_models = []
Find.find(dir) do |fpath|
... |
require 'test_helper'
class PersonTest < ActiveSupport::TestCase
test "should not save person without a first name" do
person = Person.new
assert_not person.save, "saved the person without a first name"
end
test "should not save person without assigned group" do
# test "the truth" do
# assert tr... |
# typed: false
# frozen_string_literal: true
# This file was generated by GoReleaser. DO NOT EDIT.
class Nostromo < Formula
desc "nostromo is a CLI to manage aliases through simple commands to add and remove scoped aliases and substitutions."
homepage "https://nostromo.sh"
version "0.12.0"
license "MIT"
on_... |
Given /^there is a market called "([^"]*)"$/ do |name|
@market = Factory(:market, :name => name)
end |
require_relative 'player'
module StudioGame
class ClumsyPlayer < Player
attr_reader :boost
def initialize(name, health = 100, boost = 1)
super(name, health)
@boost = boost
end
def w00t
@boost.times { super }
end
def found_treasure(treasure)
super(Treasure.new(treas... |
json.array!(@accountants) do |accountant|
json.extract! accountant, :id
json.url accountant_url(accountant, format: :json)
end
|
class AddTitleAndZipCodeAndCapacityToFlats < ActiveRecord::Migration
def change
add_column :flats, :title, :string
add_column :flats, :zip_code, :integer
add_column :flats, :capacity, :integer
end
end
|
class BroadcastParticipantStatusChangedJob < ApplicationJob
queue_as :default
def perform(participant_id)
participant = Participant.find(participant_id)
MessagingSchema.subscriptions.trigger(
"participantStatusChanged",
{participant_id: participant_id},
participant
)
end
end
|
module Wordy
class Job
attr_reader :attributes
def initialize(hash)
@attributes = {}
set_attributes(hash)
end
def set_attributes(hash)
@attributes.update hash
hash.each do |key, value|
metaclass.send :attr_accessor, key
if %w(delivery_date created).inc... |
# frozen_string_literal: true
class CreateNotifications < ActiveRecord::Migration[5.1]
def change
create_table :notifications do |t|
t.string :body, null: false
t.string :icon, null: false
t.belongs_to :business, index: true
t.timestamps
end
end
end
|
require_relative 'spec_helper'
describe Pool do
it 'is created with just a name attribute and has the expected default attributes' do
obj = Pool.new name: 'some name'
expect(obj.passive?).to eq true
expect(obj.pull?).to eq true
expect(obj.resource_count).to eq 0
end
it 'knows its name' do
... |
require 'spec_helper'
describe SeriesController do
describe "GET #index" do
it "populates an array of series" do
series = FactoryGirl.create(:series)
get :index
assigns(:series_plural).should eq([series])
end
it "renders the index view" do
get :index
response.should render_... |
class Dose < ActiveRecord::Base
belongs_to :cocktail
belongs_to :ingredient
validates_presence_of :cocktail_id, :ingredient_id, :description
validates :ingredient, :uniqueness => {:scope => :cocktail}
end
|
# frozen_string_literal: true
require 'nokogiri'
require 'open-uri'
# http://hotell.difi.no/api/json/brreg/enhetsregisteret?orgnr=982452716
class PublicRecordImporter
URL = 'http://w2.brreg.no/enhet/sok/detalj.jsp?orgnr=982452716'
def self.import_public_record
doc = Nokogiri::HTML(URI.open(URL))
record ... |
config = YAML.load_file(File.expand_path("../config/database.yml", __FILE__))
host, port, username, password, database = config.values_at *%w(host port username password database)
db = File.expand_path("../db", __FILE__)
begin
ActiveRecord::Base.establish_connection config.merge("database" => nil)
ActiveRecord::B... |
$:.push File.expand_path("../lib", __FILE__)
require "oauth2_provider_engine/version"
# Describe your gem and declare its dependencies:
Gem::Specification.new do |s|
s.name = "oauth2_provider_engine"
s.version = Oauth2ProviderEngine::VERSION
s.authors = ["Tim Galeckas"]
s.email = ["tim@ga... |
class Api::V1::SmDataController < Api::ApiController
respond_to :json
# == GET Social Media data collected for movie referenced by TMDB_ID
# movietech.herokuapp.com/api/v1/sm_data/<tmdb_id>
# eg: show all aggregated points for a specific tmdb_id: 276907
# movietech.herokuapp.com/api/v1/sm_data/276907
# ==... |
#
# Module:
# Information Collection.
#
module Collection
MODULE_NAME = "Information Collection"
TUPLES =
[
{"page"=>"index.html","desc"=>""},
{"page"=>"http://www.baidu.com/","desc"=>""},
]
def self.run(global)
global.debug("START #{MODULE_NAME}...")
#global.debug("#{TUPLES}...")
... |
require 'serverspec'
include Serverspec::Helper::Exec
include Serverspec::Helper::DetectOS
describe "Rethinkdb Package installation" do
it "rethinkdb package installed" do
expect(package('rethinkdb')).should_not be_installed
end
it "rethinkdb package in path" do
expect(file('/usr/local/b... |
class LikesController < ApplicationController
before_action :find_post, only: [:create]
def create
@post.likes.create(user_id: current_user.id)
redirect_to posts_path
end
def destroy
@post = Post.find(params[:id])
@like = Like.where(post_id: @post.id,user_id: current_user.id)
@like.destroy(... |
class Player
attr_reader :name, :hp
HIT_POINTS = 100
DAMAGE = 10
def initialize(name, hp = HIT_POINTS)
@name = name
@hp = hp
end
def reduce_hit_points
@hp -= DAMAGE
end
end
|
yum_package 'glibc' do
arch 'i686'
end
yum_package 'libstdc++' do
arch 'i686'
end
group node[:steamcmd][:group] do
action :create
end
user node[:steamcmd][:user] do
action :create
gid node[:steamcmd][:group]
supports manage_home: true
home node[:steamcmd][:home]
end
directory node[:steamcmd][:root_dir... |
class JbuilderPostsSerializer < JbuilderSerializer::Base
def build
json.posts posts do |post|
json.partial! JbuilderPostSerializer, post: post
end
end
end
class JbuilderPostSerializer < JbuilderSerializer::Base
def build
json.extract! post, :id, :title, :body, :watch_count
json.comments pos... |
module ApplicationHelper
def return_link(default_url, label = "返回")
url = params[:ok_url].blank? ? default_url : params[:ok_url]
link_to label, url, :class => 'btn'
end
def cancel_link(default_url)
return_link(default_url, '取消')
end
def ok_url_tag
hidden_field_tag "ok_url", params[:ok_u... |
require('MiniTest/autorun')
require('MiniTest/rg')
require_relative("../guest.rb")
class TestGuest < MiniTest::Test
def setup
@guest = Guest.new("Joe", "Purple Rain", 50)
end
def test_guest_name
assert_equal("Joe", @guest.name)
end
def test_guest_has_money
assert_equal(50, @guest.money)... |
module Ricer::Plugins::Board
class Model::Announcement
include Ricer::Base::Base
include Ricer::Base::Translates
attr_reader :thread, :date, :board, :url, :user, :title
def initialize(parts)
@thread, @date, @board, @url, @user, @title = *parts
end
def display_entry
... |
# -*- coding: utf-8 -*-
# == Schema Information
#
# Table name: sales
#
# id :integer not null, primary key
# product_id :integer not null
# number :string(255)
# amount :decimal(16, 2)
# state :string(255)
# error_code :string(255)
# pay... |
class SetLeadsPerHourDefaultValueInAllTables < ActiveRecord::Migration[5.0]
def change
change_column("in_store_promoters", "leads_per_hour", :float, :default =>"0")
change_column("isp_shifts", "leads_per_hour", :float, :default =>"0")
change_column("marketing_managers", "leads_per_hour", :float, :default ... |
class CreateFeeds < ActiveRecord::Migration
def change
create_table :feeds do |t|
t.integer :host_id, :null => false
t.string :source_url, :null => false
t.string :name
t.timestamps null: false
end
add_index :feeds, :host_id
add_index :feeds, :source_url, :unique => true
end... |
And(/^I fill in all the fields, except "([^"]*)" for dispute reason 'I was charged the wrong amount' dispute reason for french dispute$/) do |exclude_this_field_data|
# puts exclude_this_field_data
DataMagic.load 'can_dispute.yml'
# p on(DisputesPage).i_was_charged_wrong_amount(exclude_this_field_data)
@questi... |
FactoryBot.define do
factory :user do
name { 'お名前くん' }
email { 'ooo@ooo' }
password { 'oooooo' }
gender_id { 5 }
age { '3' }
end
end
|
class RecruitFeature < ApplicationRecord
belongs_to :recruit
belongs_to :feature
end
|
Rails.application.routes.draw do
devise_for :users, controllers: {sessions: 'users/sessions', registrations: 'users/registrations'}
root 'home#index'
namespace :users do
resources :stories, controller: 'stories' do
member do
get :slug
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.