repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
shirasagi/opendata
|
app/controllers/opendata/agents/pages/app/app_controller.rb
|
class Opendata::Agents::Pages::App::AppController < ApplicationController
include Cms::PageFilter::View
helper Opendata::UrlHelper
public
def index
@cur_node = @cur_page.parent.becomes_with_route
@cur_page.layout_id = @cur_node.page_layout_id || @cur_node.layout_id
@search_path = view_context.method(:search_apps_path)
@tab_display = ""
if @cur_page.appurl.present?
@tab_display = "tab_url"
else
appli = Opendata::App.find(@cur_page.id)
@app_html = appli.appfiles.where(filename: "index.html").first
if @app_html.present?
@tab_display = "tab_html"
@js_src = []
@css_src = []
@html_src = []
appli.appfiles.each do |file|
if file.format == "JS"
@js_src.push(file)
elsif file.format == "CSS"
@css_src.push(file)
elsif file.format == "HTML" or file.format == "HTM"
@html_src.push(file)
end
end
@csv = appli.appfiles.where(format: "CSV")
@json = appli.appfiles.where(format: "JSON")
end
end
if @cur_page.dataset_ids.empty? == false
@ds = Opendata::Dataset.site(@cur_site).public.in(id: @cur_page.dataset_ids)
end
@app_idea = Opendata::Idea.site(@cur_site).public.where(app_ids: @cur_page.id)
render
end
end
|
shirasagi/opendata
|
lib/voice/text_to_speech_factory.rb
|
<reponame>shirasagi/opendata
class Voice::TextToSpeechFactory
class << self
public
def create(type, config = {})
Voice::OpenJtalk.new(config)
end
end
end
|
shirasagi/opendata
|
spec/models/cms/site_spec.rb
|
require 'spec_helper'
describe Cms::Site do
subject(:model) { Cms::Site }
subject(:factory) { :ss_site }
it_behaves_like "mongoid#save"
it_behaves_like "mongoid#find"
describe "#attributes" do
subject(:item) { model.last }
it { expect(item.domain).not_to eq nil }
it { expect(item.path).not_to eq nil }
it { expect(item.url).not_to eq nil }
it { expect(item.full_url).not_to eq nil }
end
context "when multiple rooted site is given" do
let(:group1) { create(:cms_group, name: unique_id) }
let(:group2) { create(:cms_group, name: unique_id) }
subject do
create(:cms_site, name: unique_id, host: unique_id,
domains: ["#{unique_id}.example.jp"], group_ids: [group1.id, group2.id])
end
it { expect { subject.root_group }.to raise_error SS::Model::Site::MultipleRootGroupsError }
end
end
|
shirasagi/opendata
|
spec/factories/cms/parts.rb
|
FactoryGirl.define do
trait :cms_part do
site_id { cms_site.id }
user_id { cms_user.id }
name "#{unique_id}"
filename { "#{name}.part.html" }
route "cms/free"
end
factory :cms_part, class: Cms::Part, traits: [:cms_part] do
mobile_view :show
end
factory :cms_part_base, class: Cms::Part::Base, traits: [:cms_part] do
route "cms/base"
end
factory :cms_part_free, class: Cms::Part::Free, traits: [:cms_part] do
route "cms/free"
end
factory :cms_part_node, class: Cms::Part::Node, traits: [:cms_part] do
route "cms/node"
end
factory :cms_part_page, class: Cms::Part::Page, traits: [:cms_part] do
route "cms/page"
end
factory :cms_part_tabs, class: Cms::Part::Tabs, traits: [:cms_part] do
route "cms/tabs"
end
factory :cms_part_crumb, class: Cms::Part::Crumb, traits: [:cms_part] do
route "cms/crumb"
end
end
|
shirasagi/opendata
|
spec/features/opendata/agents/nodes/idea/search_idea_spec.rb
|
require 'spec_helper'
describe "opendata_search_ideas", dbscope: :example, js: true do
let(:site) { cms_site }
let(:layout) { create_cms_layout }
let(:node_idea) { create :opendata_node_idea, cur_site: site, layout_id: layout.id }
let!(:node_idea_search) { create(:opendata_node_search_idea, cur_site: site, cur_node: node_idea, layout_id: layout.id) }
let(:index_path) { "#{node_idea_search.url}index.html" }
let(:rss_path) { "#{node_idea_search.url}rss.xml" }
let!(:node_category_folder) { create(:cms_node_node, cur_site: site, layout_id: layout.id) }
let!(:node_category) do
create(
:opendata_node_category, cur_site: site, cur_node: node_category_folder, layout_id: layout.id,
basename: "kurashi",
name: 'カテゴリー01')
end
let!(:node_area) { create :opendata_node_area, cur_site: site, layout_id: layout.id, name: '地域A' }
before do
params = { cur_site: site, cur_node: node_idea, layout_id: layout.id, category_ids: [ node_category.id ], area_ids: [ node_area.id ] }
10.times.each do |index|
params[:issue] = "issue#{index}"
params[:text] = "text#{index}"
params[:data] = "data#{index}"
params[:note] = "note#{index}"
params[:tags] = [ "tag#{index}" ]
create :opendata_idea, params
end
end
context "search_idea" do
it "#index" do
visit index_path
expect(current_path).to eq index_path
expect(page).to have_css('.opendata-search-ideas-form')
expect(page).to have_css('.opendata-search-ideas article', count: 10)
within first('.opendata-search-ideas article') do
expect(page).to have_css('time')
expect(page).to have_css('h2 a')
expect(page).to have_css('h2 .point')
expect(page).to have_css('.categories .category')
expect(page).to have_css('.categories .area')
expect(page).to have_css('.categories .tag')
end
end
it "#index released" do
visit "#{index_path}?&sort=released"
expect(current_path).to eq index_path
expect(page).to have_css('.opendata-search-ideas-form')
expect(page).to have_css('.opendata-search-ideas article', count: 10)
within first('.opendata-search-ideas article') do
expect(page).to have_css('time')
expect(page).to have_css('h2 a')
expect(page).to have_css('h2 .point')
expect(page).to have_css('.categories .category')
expect(page).to have_css('.categories .area')
expect(page).to have_css('.categories .tag')
end
end
it "#index popular" do
visit "#{index_path}?&sort=popular"
expect(current_path).to eq index_path
expect(page).to have_css('.opendata-search-ideas-form')
expect(page).to have_css('.opendata-search-ideas article', count: 10)
within first('.opendata-search-ideas article') do
expect(page).to have_css('time')
expect(page).to have_css('h2 a')
expect(page).to have_css('h2 .point')
expect(page).to have_css('.categories .category')
expect(page).to have_css('.categories .area')
expect(page).to have_css('.categories .tag')
end
end
it "#index attention" do
visit "#{index_path}?&sort=attention"
expect(current_path).to eq index_path
expect(page).to have_css('.opendata-search-ideas-form')
expect(page).to have_css('.opendata-search-ideas article', count: 10)
within first('.opendata-search-ideas article') do
expect(page).to have_css('time')
expect(page).to have_css('h2 a')
expect(page).to have_css('h2 .point')
expect(page).to have_css('.categories .category')
expect(page).to have_css('.categories .area')
expect(page).to have_css('.categories .tag')
end
end
it "#keyword_input" do
visit index_path
fill_in "s_keyword", with: "ア<PASSWORD>"
click_button "検索"
expect(status_code).to eq 200
within first('.opendata-search-ideas article') do
expect(page).to have_css('h2', text: 'アイデアは見つかりませんでした。')
end
end
it "#keyword_input" do
visit index_path
fill_in "s_keyword", with: "text3"
click_button "検索"
expect(status_code).to eq 200
page_idea = Opendata::Idea.find_by(text: 'text3')
within first('.opendata-search-ideas article') do
expect(page).to have_css('time', text: I18n.l(page_idea.date.to_date, format: :long))
expect(page).to have_css('h2 a', text: page_idea.name)
expect(page).to have_css('h2 .point', text: page_idea.point.to_s)
expect(page).to have_css('.categories .category', text: page_idea.categories.first.name)
expect(page).to have_css('.categories .area', text: page_idea.areas.first.name)
expect(page).to have_css('.categories .tag', text: page_idea.tags.first)
end
end
it "multiple keywords_input" do
visit index_path
fill_in "s_keyword", with: "text3 text7"
select "すべてのキーワードを含む"
click_button "検索"
expect(status_code).to eq 200
expect(page).to have_css('.opendata-search-ideas article', count: 1)
within first('.opendata-search-ideas article') do
expect(page).to have_css('h2', text: 'アイデアは見つかりませんでした。')
end
select "いずれかのキーワードを含む"
click_button "検索"
expect(page).to have_css('.opendata-search-ideas article', count: 2)
end
it "#category_select" do
visit index_path
select node_category.name
click_button "検索"
expect(status_code).to eq 200
end
it "#area_select" do
visit index_path
select node_area.name
click_button "検索"
expect(status_code).to eq 200
end
it "#tag_input" do
visit index_path
fill_in "s_tag", with: "tag5"
click_button "検索"
expect(status_code).to eq 200
page_idea = Opendata::Idea.find_by(tags: 'tag5')
within first('.opendata-search-ideas article') do
expect(page).to have_css('time', text: I18n.l(page_idea.date.to_date, format: :long))
expect(page).to have_css('h2 a', text: page_idea.name)
expect(page).to have_css('h2 .point', text: page_idea.point.to_s)
expect(page).to have_css('.categories .category', text: page_idea.categories.first.name)
expect(page).to have_css('.categories .area', text: page_idea.areas.first.name)
expect(page).to have_css('.categories .tag', text: page_idea.tags.first)
end
end
it "keyword and tag input" do
visit index_path
fill_in "s_keyword", with: "text3"
fill_in "s_tag", with: "tag5"
select "すべてのキーワードを含む"
click_button "検索"
expect(status_code).to eq 200
expect(page).to have_css('.opendata-search-ideas article', count: 1)
within first('.opendata-search-ideas article') do
expect(page).to have_css('h2', text: 'アイデアは見つかりませんでした。')
end
select "いずれかのキーワードを含む"
click_button "検索"
expect(page).to have_css('.opendata-search-ideas article', count: 1)
within first('.opendata-search-ideas article') do
expect(page).to have_css('h2', text: 'アイデアは見つかりませんでした。')
end
select "すべてをOR条件で検索する"
click_button "検索"
expect(page).to have_css('.opendata-search-ideas article', count: 2)
end
it "#rss" do
visit rss_path
expect(current_path).to eq rss_path
end
end
context "when point is hide" do
before do
node_idea.show_point = 'hide'
node_idea.save!
Opendata::Idea.all.each do |page_idea|
page_idea.touch
page_idea.save!
end
end
it "#index" do
visit index_path
expect(current_path).to eq index_path
expect(page).to have_css('.opendata-search-ideas-form')
expect(page).to have_css('.opendata-search-ideas article', count: 10)
within first('.opendata-search-ideas article') do
expect(page).to have_css('time')
expect(page).to have_css('h2 a')
expect(page).not_to have_css('h2 .point')
expect(page).to have_css('.categories .category')
expect(page).to have_css('.categories .area')
expect(page).to have_css('.categories .tag')
end
end
end
end
|
shirasagi/opendata
|
app/models/concerns/opendata/addon/my_idea_list.rb
|
module Opendata::Addon::MyIdeaList
extend SS::Addon
extend ActiveSupport::Concern
include Cms::Addon::PageList
public
def template_variable_get(item, name)
if name.start_with?('idea_')
if index = name.index('.')
param = name[index + 1..-1]
name = name[0..index - 1]
end
send("get_#{name}", item, param) rescue super
else
super
end
end
private
def get_idea_name(item, *_)
ERB::Util.html_escape item.name
end
def get_idea_url(item, *_)
ERB::Util.html_escape "#{self.url}#{item.id}/"
end
def get_idea_updated(item, *args)
format = args.shift
format ||= I18n.t("opendata.labels.updated")
I18n.l item.updated, format: format
end
def get_idea_state(item, *_)
ERB::Util.html_escape(item.label :status)
end
def get_idea_point(item, *_)
ERB::Util.html_escape(item.point.to_i.to_s)
end
def get_idea_datasets(item, *_)
if item.dataset_ids.length > 0
ERB::Util.html_escape(item.datasets[0].name)
else
ERB::Util.html_escape(I18n.t("opendata.labels.not_exist"))
end
end
def get_idea_apps(item, *_)
if item.app_ids.length > 0
ERB::Util.html_escape(item.apps[0].name)
else
ERB::Util.html_escape(I18n.t("opendata.labels.not_exist"))
end
end
def get_idea_ideas_count(item, *_)
ERB::Util.html_escape(item.ideas.size.to_s)
end
end
|
shirasagi/opendata
|
app/models/concerns/opendata/addon/my_dataset_list.rb
|
<filename>app/models/concerns/opendata/addon/my_dataset_list.rb
module Opendata::Addon::MyDatasetList
extend SS::Addon
extend ActiveSupport::Concern
include Cms::Addon::PageList
public
def template_variable_get(item, name)
if name.start_with?('dataset_')
if name == 'dataset_name'
ERB::Util.html_escape item.name
elsif name == 'dataset_url'
ERB::Util.html_escape "#{self.url}#{item.id}/"
elsif name == 'dataset_updated'
I18n.l item.updated, format: I18n.t("opendata.labels.updated")
elsif name =~ /^dataset_updated\.(.+)$/
I18n.l item.updated, format: $1
elsif name == 'dataset_state'
ERB::Util.html_escape(item.label :status)
elsif name == 'dataset_point'
ERB::Util.html_escape(item.point.to_i.to_s)
elsif name == 'dataset_downloaded'
ERB::Util.html_escape(item.downloaded.to_i.to_s)
elsif name == 'dataset_apps_count'
ERB::Util.html_escape(item.apps.size.to_s)
elsif name == 'dataset_ideas_count'
ERB::Util.html_escape(item.ideas.size.to_s)
else
false
end
else
super
end
end
end
|
shirasagi/opendata
|
app/models/chorg/initializer.rb
|
module Chorg
class Initializer
end
end
|
shirasagi/opendata
|
spec/models/ldap/import_job_spec.rb
|
require 'spec_helper'
describe Ldap::ImportJob, ldap: true do
describe "#call" do
context "when no ldap connection is set" do
subject { Ldap::ImportJob.new }
it "should not raise errors" do
expect { subject.call(cms_site.id, cms_user.id, "pass") }.to raise_error
end
end
context "when ldap connection is set" do
let(:group) do
create(:cms_group, name: unique_id, ldap_dn: "dc=city,dc=shirasagi,dc=jp")
end
let(:site) do
create(:cms_site, name: unique_id, host: unique_id, domains: ["#{unique_id}.example.jp"],
group_ids: [group.id])
end
let(:role) do
create(:cms_user_role, name: "ldap_user_role_#{unique_id}", site_id: site.id)
end
let(:user) do
create(:cms_user, name: unique_id, email: <EMAIL>", in_password: "<PASSWORD>",
group_ids: [group.id], cms_role_ids: [role.id])
end
subject { Ldap::ImportJob.new }
around(:each) do |example|
save_auth_method = SS.config.ldap.auth_method
SS.config.replace_value_at(:ldap, :auth_method, "anonymous")
example.run
SS.config.replace_value_at(:ldap, :auth_method, save_auth_method)
end
import = nil
it "should not raise errors" do
expect { import = subject.call(site.id, user.id, "pass") }.not_to raise_error
end
it "should return non-nil" do
expect(import).not_to be_nil
end
end
end
end
|
shirasagi/opendata
|
app/controllers/concerns/ss/trans_sid_filter.rb
|
module SS::TransSidFilter
extend ActiveSupport::Concern
included do
if defined?(Jpmobile)
before_action :set_trans_sid
trans_sid :none
end
end
private
def mobile_path?
filters = request.env["ss.filters"]
return false if filters.blank?
filters.include?(:mobile)
end
def set_trans_sid
case SS.config.mobile.trans_sid.to_sym
when :always
self.trans_sid_mode = :always
when :mobile
if mobile_path?
self.trans_sid_mode = :mobile
end
end
end
end
|
shirasagi/opendata
|
spec/features/rdf/props_spec.rb
|
require 'spec_helper'
describe "rdf_props", type: :feature, dbscope: :example do
let(:site) { cms_site }
let!(:category) { create(:opendata_node_category, cur_site: site) }
let(:vocab) { create(:rdf_vocab, site: site) }
let(:index_path) { rdf_props_props_path site.host, vocab.id }
let(:new_path) { new_rdf_props_prop_path site.host, vocab.id }
it "without login" do
visit index_path
expect(current_path).to eq sns_login_path
end
it "without auth" do
login_ss_user
visit index_path
expect(status_code).to eq 403
end
context "with auth" do
before { login_cms_user }
context "without class" do
describe "#index" do
it do
visit index_path
expect(current_path).to eq index_path
end
end
describe "#new" do
it do
visit new_path
within "form#item-form" do
fill_in "item[name]", with: "#{unique_id}"
fill_in "item[labels][ja]", with: "#{unique_id}"
click_button I18n.t("views.button.save")
end
expect(status_code).to eq 200
expect(current_path).not_to eq new_path
expect(page).not_to have_css("form#item-form")
end
end
describe "#show" do
let(:item) { create(:rdf_prop, vocab: vocab) }
let(:show_path) { rdf_props_prop_path site.host, vocab.id, item }
it do
visit show_path
expect(status_code).to eq 200
expect(current_path).to eq show_path
end
end
describe "#edit" do
let(:item) { create(:rdf_prop, vocab: vocab) }
let(:edit_path) { edit_rdf_props_prop_path site.host, vocab.id, item }
it do
visit edit_path
within "form#item-form" do
fill_in "item[labels][ja]", with: "modify"
click_button I18n.t("views.button.save")
end
expect(current_path).not_to eq sns_login_path
expect(page).not_to have_css("form#item-form")
end
end
describe "#delete" do
let(:item) { create(:rdf_prop, vocab: vocab) }
let(:delete_path) { delete_rdf_props_prop_path site.host, vocab.id, item }
it do
visit delete_path
within "form" do
click_button I18n.t("views.button.delete")
end
expect(current_path).to eq index_path
end
end
end
context "with class" do
let(:rdf_class) { create(:rdf_class, vocab: vocab) }
let(:index_path) { rdf_classes_props_props_path site.host, vocab.id, rdf_class.id }
let(:new_path) { new_rdf_classes_props_prop_path site.host, vocab.id, rdf_class.id }
describe "#index" do
it do
visit index_path
expect(current_path).to eq index_path
end
end
describe "#new" do
it do
visit new_path
within "form#item-form" do
fill_in "item[name]", with: "#{unique_id}"
fill_in "item[labels][ja]", with: "#{unique_id}"
click_button I18n.t("views.button.save")
end
expect(status_code).to eq 200
expect(current_path).not_to eq new_path
expect(page).not_to have_css("form#item-form")
end
end
describe "#show" do
let(:item) { create(:rdf_prop, vocab: vocab, rdf_class: rdf_class) }
let(:show_path) { rdf_classes_props_prop_path site.host, vocab.id, rdf_class.id, item }
it do
visit show_path
expect(status_code).to eq 200
expect(current_path).to eq show_path
end
end
describe "#edit" do
let(:item) { create(:rdf_prop, vocab: vocab, rdf_class: rdf_class) }
let(:edit_path) { edit_rdf_classes_props_prop_path site.host, vocab.id, rdf_class.id, item }
it do
visit edit_path
within "form#item-form" do
fill_in "item[labels][ja]", with: "modify"
click_button I18n.t("views.button.save")
end
expect(current_path).not_to eq sns_login_path
expect(page).not_to have_css("form#item-form")
end
end
describe "#unlink" do
let(:item) { create(:rdf_prop, vocab: vocab, rdf_class: rdf_class) }
let(:unlink_path) { unlink_rdf_classes_props_prop_path site.host, vocab.id, rdf_class.id, item }
it do
visit unlink_path
within "form" do
click_button I18n.t("views.button.delete")
end
expect(current_path).to eq index_path
within "table.index" do
expect(page).not_to have_text(item.name)
end
end
end
describe "#import" do
let!(:item) { create(:rdf_prop, vocab: vocab) }
let(:import_path) { import_rdf_classes_props_props_path site.host, vocab.id, rdf_class.id }
it do
visit import_path
within "form#item-form" do
check "item_ids_#{item.id}"
click_button I18n.t("rdf.button.import")
end
expect(current_path).to eq index_path
within "table.index" do
expect(page).to have_text(item.name)
end
end
end
end
end
end
|
shirasagi/opendata
|
spec/factories/article/pages.rb
|
<filename>spec/factories/article/pages.rb
FactoryGirl.define do
factory :article_page, class: Article::Page, traits: [:cms_page] do
transient do
site nil
node nil
end
cur_site { site ? site : cms_site }
filename { node ? "#{node.filename}/#{name}.html" : "dir/#{unique_id}.html" }
route "article/page"
end
end
|
shirasagi/opendata
|
app/controllers/concerns/ss/auth_filter.rb
|
<reponame>shirasagi/opendata<filename>app/controllers/concerns/ss/auth_filter.rb
module SS::AuthFilter
extend ActiveSupport::Concern
included do
cattr_accessor(:user_class) { SS::User }
end
public
def get_user_by_session
return nil unless session[:user]
u = SS::Crypt.decrypt(session[:user]).to_s.split(",", 3)
#return unset_user redirect: true if u[1] != remote_addr.to_s
#return unset_user redirect: true if u[2] != request.user_agent.to_s
self.user_class.find u[0].to_i rescue nil
end
end
|
shirasagi/opendata
|
app/controllers/concerns/opendata/idea/comment_filter.rb
|
<gh_stars>1-10
module Opendata::Idea::CommentFilter
extend ActiveSupport::Concern
private
def update_commented_count(member_ids, count)
member_ids.each do |member_id|
notice = Opendata::MemberNotice.where({site_id: @cur_site.id, member_id: member_id}).first
if notice
notice.commented_count += count
notice.save
else
notice_new = { site_id: @cur_site.id, member_id: member_id, commented_count: 1 }
Opendata::MemberNotice.new(notice_new).save
end
end
end
public
def update_member_notices(idea)
except_member_ids = []
except_member_ids << @cur_member.id if @cur_member
except_member_ids << idea.member_id if idea.member_id
member_ids = []
other_comments = Opendata::IdeaComment.where({idea_id: idea.id})
other_comments.each do |other_comment|
other_member_id = other_comment.member_id
if other_member_id && except_member_ids.include?(other_member_id) == false
member_ids << other_comment.member_id
end
end
if @cur_member
if idea.member_id && idea.member_id != @cur_member.id
member_ids << idea.member_id
end
else
if idea.member_id
member_ids << idea.member_id
end
end
update_commented_count(member_ids.uniq, 1)
end
end
|
shirasagi/opendata
|
spec/features/cms/contents_spec.rb
|
<reponame>shirasagi/opendata
require 'spec_helper'
describe "cms_contents", dbscope: :example, type: :feature do
subject(:site) { cms_site }
subject(:index_path) { cms_contents_path site.host }
it "without login" do
visit index_path
expect(current_path).to eq sns_login_path
end
it "without auth" do
login_ss_user
visit index_path
expect(status_code).to eq 403
end
context "with auth" do
before { login_cms_user }
it "#index" do
visit index_path
expect(status_code).to eq 200
expect(current_path).to eq index_path
end
end
context "with notice" do
let!(:normal_notice) { create(:cms_notice, notice_severity: Cms::Notice::NOTICE_SEVERITY_NORMAL) }
let!(:high_notice) { create(:cms_notice, notice_severity: Cms::Notice::NOTICE_SEVERITY_HIGH) }
# subject(:notice_path) { notice_cms_content_path site.host, item }
before do
login_cms_user
end
it "#index and #notice" do
visit index_path
expect(status_code).to eq 200
expect(current_path).not_to eq sns_login_path
within "table.notices-severity-high" do
expect(page).to have_content(high_notice.name)
expect(page).not_to have_content(normal_notice.name)
end
within "table.notices-severity-normal" do
expect(page).not_to have_content(high_notice.name)
expect(page).to have_content(normal_notice.name)
end
within "table.notices-severity-high" do
click_link high_notice.name
end
within "div.addon-view" do
expect(page).to have_content(high_notice.name)
end
end
end
end
|
shirasagi/opendata
|
app/controllers/rdf/apis/classes_controller.rb
|
<reponame>shirasagi/opendata
class Rdf::Apis::ClassesController < ApplicationController
include Cms::ApiFilter
model Rdf::Class
before_action :set_vocab_id
private
def vocab_options
vocabs = Rdf::Vocab.site(@cur_site).each.select do |vocab|
vocab.allowed?(:read, @cur_user, site: @cur_site)
end
vocabs.reduce([]) do |ret, vocab|
ret << [ vocab.labels.preferred_value, vocab.id ]
end.to_a
end
def set_vocab_id
params[:s] = {} if params[:s].blank?
params[:s][:vocab] = Rdf::Vocab.site(@cur_site).first.id if params[:s][:vocab].blank?
end
public
def index
@target = params[:target]
@vocab_options = vocab_options
@items = @model.site(@cur_site).search(params[:s]).page(params[:page]).per(50)
end
end
|
shirasagi/opendata
|
app/controllers/opendata/agents/parts/idea/idea_controller.rb
|
<filename>app/controllers/opendata/agents/parts/idea/idea_controller.rb
class Opendata::Agents::Parts::Idea::IdeaController < ApplicationController
include Cms::PartFilter::View
include Opendata::UrlHelper
helper Opendata::ListHelper
public
def index
@node_url = "#{search_ideas_path}?sort=#{@cur_part.sort}"
default_options = { "sort" => "#{@cur_part.sort}" }
@rss_path = ->(options = {}) { build_path("#{search_ideas_path}rss.xml", default_options.merge(options)) }
@items = Opendata::Idea.site(@cur_site).public.
where(@cur_part.condition_hash).
sort_criteria(@cur_part.sort).
page(params[:page]).
per(@cur_part.limit)
render
end
end
|
shirasagi/opendata
|
app/controllers/concerns/cms/searchable_crud_filter.rb
|
<filename>app/controllers/concerns/cms/searchable_crud_filter.rb
module Cms::SearchableCrudFilter
extend ActiveSupport::Concern
public
def index
raise "403" unless @model.allowed?(:read, @cur_user, site: @cur_site)
@items = @model.site(@cur_site).
allow(:edit, @cur_user, site: @cur_site).
search(params[:s]).
order_by(name: 1).
page(params[:page]).per(50)
end
end
|
shirasagi/opendata
|
app/models/ldap/extensions/ldap_entity.rb
|
class Ldap::Extensions::LdapEntity < Hash
def mongoize
self.to_h
end
class << self
def demongoize(object)
if object.present?
ret = Ldap::Extensions::LdapEntity.new
object.symbolize_keys.each do |key, value|
ret[key] = value
end
ret
else
Ldap::Extensions::LdapEntity.new
end
end
def mongoize(object)
case object
when self.class then
object.mongoize
when Hash then
object.symbolize_keys
else
object
end
end
def convert_group(ldap_group, parent_dn: nil)
entity = new
entity[:type] = Ldap::Import::TYPE_GROUP
entity[:dn] = ldap_group.dn
entity[:name] = ldap_group.name
entity[:contact_tel] = ldap_group.contact_tel
entity[:parent_dn] = parent_dn if parent_dn.present?
entity
end
def convert_user(ldap_user, parent_dn: nil)
entity = new
entity[:type] = Ldap::Import::TYPE_USER
entity[:dn] = ldap_user.dn
entity[:name] = ldap_user.name
entity[:uid] = ldap_user.uid
entity[:email] = ldap_user.email
entity[:parent_dn] = parent_dn if parent_dn.present?
entity
end
end
def type
self[:type]
end
def dn
self[:dn]
end
def name
self[:name]
end
def uid
self[:uid]
end
def email
self[:email]
end
def contact_tel
self[:contact_tel]
end
def contact_fax
nil
end
alias_method :contact_email, :email
end
|
shirasagi/opendata
|
app/models/concerns/cms/addon/import/group.rb
|
<reponame>shirasagi/opendata<filename>app/models/concerns/cms/addon/import/group.rb
require "csv"
module Cms::Addon::Import
module Group
extend ActiveSupport::Concern
extend SS::Addon
included do
attr_accessor :in_file, :imported
permit_params :in_file
end
module ClassMethods
public
def to_csv
csv = CSV.generate do |data|
data << %w(id name order ldap_dn contact_tel contact_fax contact_email)
criteria.each do |item|
line = []
line << item.id
line << item.name
line << item.order
line << item.ldap_dn
line << item.contact_tel
line << item.contact_fax
line << item.contact_email
data << line
end
end
end
end
private
def validate_import
return errors.add :in_file, :blank if in_file.blank?
fname = in_file.original_filename
return errors.add :in_file, :invalid_file_type if ::File.extname(fname) !~ /^\.csv$/i
begin
table = CSV.read(in_file.path, headers: true, encoding: 'SJIS:UTF-8')
in_file.rewind
rescue => e
errors.add :in_file, :invalid_file_type
end
end
def update_row(row, index)
id = row["id"].to_s.strip
name = row["name"].to_s.strip
order = row["order"].to_s.strip
ldap_dn = row["ldap_dn"].to_s.strip
contact_tel = row["contact_tel"].to_s.strip
contact_fax = row["contact_fax"].to_s.strip
contact_email = row["contact_email"].to_s.strip
if id.present?
item = self.class.where(id: id).first
if item.blank?
e = I18n.t("errors.messages.invalid")
self.errors.add :base, "#{index}: #{t(:id)}#{e}"
return nil
end
if name.blank?
item.destroy
@imported += 1
return nil
end
else
item = self.class.new
end
item.name = name
item.order = order
item.ldap_dn = ldap_dn
item.contact_tel = contact_tel
item.contact_fax = contact_fax
item.contact_email = contact_email
if item.save
@imported += 1
else
set_errors(item, index)
end
item
end
def set_errors(item, index)
error = ""
item.errors.each do |n, e|
error += "#{item.class.t(n)}#{e} "
end
self.errors.add :base, "#{index}: #{error}"
end
public
def import
@imported = 0
validate_import
return false unless errors.empty?
table = CSV.read(in_file.path, headers: true, encoding: 'SJIS:UTF-8')
table.each_with_index do |row, i|
item = update_row(row, i + 2)
end
return errors.empty?
end
end
end
|
shirasagi/opendata
|
app/models/concerns/rdf/object.rb
|
module Rdf::Object
extend ActiveSupport::Concern
extend SS::Translation
include SS::Document
include Rdf::Reference::Vocab
included do
seqid :id
field :name, type: String
field :labels, type: Rdf::Extensions::LangHash
field :comments, type: Rdf::Extensions::LangHash
permit_params :name, :labels, :comments
permit_params labels: Rdf::Extensions::LangHash::LANGS
permit_params comments: Rdf::Extensions::LangHash::LANGS
before_validation :normalize_name
validates :name, presence: true, length: { maximum: 80 }, uniqueness: { scope: :vocab_id }
validate :validate_name
scope :prefix_and_name, ->(prefix, name) { self.in(vocab_id: Rdf::Vocab.where(prefix: prefix).pluck(:id)).where(name: name) }
end
module ClassMethods
def search(params)
criteria = search_vocab(params)
return criteria if params.blank?
words = params[:name]
words ||= params[:keyword]
if words.present?
words = words.split(/[\s ]+/).uniq.compact.map { |w| /\Q#{Regexp.escape(w)}\E/i } if words.is_a?(String)
criteria = criteria.all_in(name: words)
end
class_id = params[:class_id]
if class_id.present?
class_id = class_id.to_i if class_id.respond_to?(:to_i)
criteria = criteria.in(class_ids: [class_id])
end
uri = params[:uri]
if uri.present?
prefix, name = Rdf::Vocab.qname(uri)
criteria = criteria.prefix_and_name(prefix, name)
end
category_id = params[:category]
if category_id.present?
category_id = category_id.to_i if category_id.respond_to?(:to_i)
criteria = criteria.in(category_ids: [category_id])
end
category_ids = params[:category_ids]
if category_ids.present?
# false means all
category_ids = category_ids.map { |e| e == "false" ? false : e.to_i }
criteria = criteria.in(category_ids: category_ids) unless category_ids.include?(false)
end
criteria
end
end
private
def normalize_name
return if name.blank?
# name must be NFKC
self.name = UNF::Normalizer.normalize(self.name.strip, :nfkc)
end
def validate_name
return if name.blank?
# symbols is not allowed.
errors.add :name, :invalid if name =~ /[\x00-,:-@\[-\^`\{-\x7f]/
end
public
# view support method
def preferred_label
"#{vocab.prefix}:#{name}"
end
def uri
"#{vocab.uri}#{name}"
end
end
|
shirasagi/opendata
|
lib/ldap/entry.rb
|
class Ldap::Entry
include Enumerable
include Comparable
def initialize(connection, entry)
@connection = connection
@entry = entry
end
class << self
def find(connection, dn)
connection.find(dn, self)
end
end
def dn
self.class.normalize(@entry.dn)
end
def [](name)
self.class.normalize(@entry[name])
end
alias_method :values, :[]
def value(name)
self[name].first
end
def each
@entry.each do |key, values|
yield self.class.normalize(key), self.class.normalize(values)
end
end
def parent
_, parent_dn = Ldap::Connection.split_dn(dn)
Ldap::Group.find(@connection, parent_dn)
end
def self.normalize(e)
if e.kind_of?(String)
e.force_encoding("UTF-8")
elsif e.kind_of?(Array)
e.map do |v|
normalize(v)
end
else
e
end
end
def <=>(other)
dn <=> other.dn
end
end
|
shirasagi/opendata
|
spec/factories/key_visual/pages.rb
|
<filename>spec/factories/key_visual/pages.rb
FactoryGirl.define do
factory :key_visual_image, class: KeyVisual::Image, traits: [:cms_page] do
filename { "dir/#{unique_id}" }
route "key_visual/image"
link_url "/example/"
file_id 1
end
end
|
shirasagi/opendata
|
spec/features/opendata/licenses_spec.rb
|
require 'spec_helper'
describe "opendata_licenses", type: :feature, dbscope: :example do
let(:site) { cms_site }
let(:node) { create_once :opendata_node_dataset, name: "opendata_dataset" }
let(:index_path) { opendata_licenses_path site.host, node }
let(:new_path) { new_opendata_license_path site.host, node }
it "without login" do
visit index_path
expect(current_path).to eq sns_login_path
end
it "without auth" do
login_ss_user
visit index_path
expect(status_code).to eq 403
end
context "with auth" do
before { login_cms_user }
describe "#index" do
it do
visit index_path
expect(current_path).not_to eq sns_login_path
end
end
describe "#new" do
it do
visit new_path
within "form#item-form" do
fill_in "item[name]", with: "sample"
attach_file "item[in_file]", "#{Rails.root}/spec/fixtures/ss/logo.png"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).not_to eq new_path
expect(page).not_to have_css("form#item-form")
end
end
describe "#show" do
let(:license_logo_file_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png") }
let(:license_logo_file) { Fs::UploadedFile.create_from_file(license_logo_file_path, basename: "spec") }
let(:item) { create(:opendata_license, site: site, file: license_logo_file) }
let(:show_path) { opendata_license_path site.host, node, item }
it do
visit show_path
expect(status_code).to eq 200
expect(current_path).not_to eq sns_login_path
end
end
describe "#edit" do
let(:license_logo_file_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png") }
let(:license_logo_file) { Fs::UploadedFile.create_from_file(license_logo_file_path, basename: "spec") }
let(:item) { create(:opendata_license, site: site, file: license_logo_file) }
let(:edit_path) { edit_opendata_license_path site.host, node, item }
it do
visit edit_path
within "form#item-form" do
fill_in "item[name]", with: "modify"
click_button "保存"
end
expect(current_path).not_to eq sns_login_path
expect(page).not_to have_css("form#item-form")
end
end
describe "#delete" do
let(:license_logo_file_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png") }
let(:license_logo_file) { Fs::UploadedFile.create_from_file(license_logo_file_path, basename: "spec") }
let(:item) { create(:opendata_license, site: site, file: license_logo_file) }
let(:delete_path) { delete_opendata_license_path site.host, node, item }
it do
visit delete_path
within "form" do
click_button "削除"
end
expect(current_path).to eq index_path
end
end
end
end
|
shirasagi/opendata
|
app/helpers/application_helper.rb
|
module ApplicationHelper
def tryb(&block)
begin
block.call
rescue NoMethodError
nil
end
end
def t(key, opts = {})
opts[:scope] = [:views] if key !~ /\./ && !opts[:scope]
I18n.t key, opts.merge(default: key.to_s.humanize)
end
def br(str)
h(str.to_s).gsub(/(\r\n?)|(\n)/, "<br />").html_safe
end
def snip(str, opt = {})
len = opt[:length] || 80
"#{str.to_s[0..len-1]}#{str.to_s.size > len ? ".." : ""}".html_safe
end
def current_url?(url)
current = @cur_path.sub(/\?.*/, "")
return nil if current.gsub("/", "").blank?
return :current if url.sub(/\/index\.html$/, "/") == current.sub(/\/index\.html$/, "/")
return :current if current =~ /^#{Regexp.escape(url)}(\/|\?|$)/
nil
end
def link_to(*args)
if args[0].class == Symbol
args[0] = I18n.t "views.links.#{args[0]}", default: nil || t(args[0])
end
super *args
end
def url_for(*args)
url = super
if SS::MobileSupport.mobile?(request)
url = SS::MobileSupport.embed_mobile_path(request, url)
end
url
end
def jquery(&block)
javascript_tag do
"$(function() {\n#{capture(&block)}\n});".html_safe
end
end
# @deprecated
def coffee(&block)
javascript_tag do
CoffeeScript.compile(capture(&block)).html_safe
end
end
# @deprecated
def scss(&block)
opts = Rails.application.config.sass
sass = Sass::Engine.new "@import 'compass/css3';\n" + capture(&block),
syntax: :scss,
cache: false,
style: :compressed,
debug_info: false,
load_paths: opts.load_paths[1..-1] + ["#{Gem.loaded_specs['compass'].full_gem_path}/frameworks/compass/stylesheets"]
h = []
h << "<style>"
h << sass.render
h << "</style>"
h.join("\n").html_safe
end
def tt(key, html_wrap = true)
msg = I18n.t("tooltip.#{key}", default: "")
return msg if msg.blank? || !html_wrap
msg = [msg] if msg.class.to_s == "String"
list = msg.map {|d| "<li>" + d.gsub(/\r\n|\n/, "<br />") + "</li>"}
h = []
h << %(<div class="tooltip">?)
h << %(<ul>)
h << list
h << %(</ul>)
h << %(</div>)
h.join("\n").html_safe
end
def render_agent(controller_name, action)
controller.render_agent(controller_name, action).body.html_safe
end
def mail_to_entity(email_address, name = nil, html_options = {}, &block)
html_options, name = name, nil if block_given?
html_options = (html_options || {}).stringify_keys
extras = %w(cc bcc body subject).map! do |item|
option = html_options.delete(item) || next
"#{item}=#{Rack::Utils.escape_path(option)}"
end.compact
extras = extras.empty? ? '' : '?' + extras.join('&')
email_address = email_address.gsub(/@/, "@").gsub(/\./, ".").html_safe if email_address.present?
html_options["href"] = "mailto:#{email_address}#{extras}".html_safe
content_tag(:a, name || email_address, html_options, &block)
end
end
|
shirasagi/opendata
|
spec/helpers/opendata/url_helper_spec.rb
|
<gh_stars>1-10
require 'spec_helper'
describe Opendata::UrlHelper, type: :helper, dbscope: :example do
let(:icon_file_path) { "#{Rails.root}/spec/fixtures/ss/logo.png" }
let(:icon_file) { Fs::UploadedFile.create_from_file(icon_file_path) }
describe ".member_icon" do
context "when menber has icon" do
let(:member) { create(:opendata_member, icon_file: icon_file) }
subject { helper.member_icon(member) }
it { is_expected.to eq '<img alt="" src="/fs/1/_/logo.png" />' }
end
context "when menber doesn't have icon" do
let(:member) { create(:opendata_member) }
subject { helper.member_icon(member) }
it { is_expected.to eq '<img alt="" src="/assets/opendata/icon-user.png" />' }
end
context "when size parameter is given" do
let(:member) { create(:opendata_member) }
subject { helper.member_icon(member, size: :small) }
it { is_expected.to eq '<img alt="" width="38" height="38" src="/assets/opendata/icon-user.png" />' }
end
context "when alt parameter is given" do
let(:member) { create(:opendata_member) }
subject { helper.member_icon(member, alt: "alt") }
it { is_expected.to eq '<img alt="alt" src="/assets/opendata/icon-user.png" />' }
end
end
describe ".build_path" do
context "when sort parameter is given" do
subject { helper.build_path "/dataset/search/", "sort" => "popular" }
it { is_expected.to eq "/dataset/search/?sort=popular" }
end
context "when s[area] parameter is given" do
subject { helper.build_path "/dataset/search/", "s[area]" => "32" }
it { is_expected.to eq "/dataset/search/?s%5Barea%5D=32" }
end
context "when s[tag] parameter is given" do
subject { helper.build_path "/dataset/search/", "s[tag]" => "人口" }
it { is_expected.to eq "/dataset/search/?s%5Btag%5D=%E4%BA%BA%E5%8F%A3" }
end
context "when s[format] parameter is given" do
subject { helper.build_path "/dataset/search/", "s[format]" => "XLS" }
it { is_expected.to eq "/dataset/search/?s%5Bformat%5D=XLS" }
end
context "when s[license] parameter is given" do
subject { helper.build_path "/dataset/search/", "s[license]" => "2" }
it { is_expected.to eq "/dataset/search/?s%5Blicense%5D=2" }
end
context "when composite parameters is given" do
subject do
helper.build_path "/dataset/search/",
"sort" => "popular",
"s[area]" => "32",
"s[tag]" => "人口"
end
it { is_expected.to eq "/dataset/search/?s%5Barea%5D=32&s%5Btag%5D=%E4%BA%BA%E5%8F%A3&sort=popular" }
end
end
describe ".search_datasets_path" do
before do
@cur_site = cms_site
@search_dataset = create :opendata_node_search_dataset
end
subject { helper.search_datasets_path }
it { is_expected.to eq @search_dataset.url }
end
describe ".search_groups_path" do
before do
@cur_site = cms_site
@search_dataset_group = create :opendata_node_search_dataset_group
end
subject { helper.search_groups_path }
it { is_expected.to eq @search_dataset_group.url }
end
describe ".search_apps_path" do
before do
@cur_site = cms_site
@search_app = create :opendata_node_search_app
end
subject { helper.search_apps_path }
it { is_expected.to eq @search_app.url }
end
describe ".search_ideas_path" do
before do
@cur_site = cms_site
@search_idea = create :opendata_node_search_idea
end
subject { helper.search_ideas_path }
it { is_expected.to eq @search_idea.url }
end
describe ".sparql_path" do
before do
@cur_site = cms_site
@sparql = create :opendata_node_sparql
end
subject { helper.sparql_path }
it { is_expected.to eq @sparql.url }
end
describe ".mypage_path" do
before do
@cur_site = cms_site
@mypage = create :opendata_node_mypage
end
subject { helper.mypage_path }
it { is_expected.to eq @mypage.url }
end
describe ".member_path" do
before do
@cur_site = cms_site
@member = create :opendata_node_member
end
subject { helper.member_path }
it { is_expected.to eq @member.url }
end
describe ".mypage_path" do
before do
@cur_site = cms_site
@mypage = create :opendata_node_mypage
end
subject { helper.mypage_path }
it { is_expected.to eq @mypage.url }
end
end
|
shirasagi/opendata
|
app/models/concerns/cms/model/page.rb
|
module Cms::Model::Page
extend ActiveSupport::Concern
extend SS::Translation
include Cms::Content
include Cms::Reference::Layout
included do
class_variable_set(:@@_after_generate_file_callbacks, [])
class_variable_set(:@@_after_remove_file_callbacks, [])
class_variable_set(:@@_after_rename_file_callbacks, [])
store_in collection: "cms_pages"
set_permission_name "cms_pages"
#text_index :name, :html
field :route, type: String, default: ->{ "cms/page" }
embeds_ids :categories, class_name: "Cms::Node"
permit_params category_ids: []
after_validation :set_released, if: -> { public? }
after_save :rename_file, if: ->{ @db_changes }
after_save :generate_file, if: ->{ @db_changes }
after_save :remove_file, if: ->{ @db_changes && @db_changes["state"] && !public? }
after_destroy :remove_file
end
private
def run_callback(c, *args)
call = true
call = instance_exec(&c[:if]) if c[:if]
call = !instance_exec(&c[:unless]) if c[:unless]
send(c[:method], *args) if call
end
public
def date
released || updated || created
end
def generate_file
return false unless serve_static_file?
return false unless public?
return false unless public_node?
written = Cms::Agents::Tasks::PagesController.new.generate_page(self)
self.class.class_variable_get(:@@_after_generate_file_callbacks).each do |c|
run_callback(c)
end
written
end
def remove_file
Fs.rm_rf path
self.class.class_variable_get(:@@_after_remove_file_callbacks).each do |c|
run_callback(c)
end
end
def rename_file
return unless @db_changes["filename"]
return unless @db_changes["filename"][0]
src = "#{site.path}/#{@db_changes['filename'][0]}"
dst = "#{site.path}/#{@db_changes['filename'][1]}"
dst_dir = ::File.dirname(dst)
Fs.mkdir_p dst_dir unless Fs.exists?(dst_dir)
Fs.mv src, dst if Fs.exists?(src)
self.class.class_variable_get(:@@_after_rename_file_callbacks).each do |c|
run_callback(c, src, dst)
end
end
def validate_destination_filename(dst)
dst_dir = ::File.dirname(dst).sub(/^\.$/, "")
return errors.add :filename, :empty if dst.blank?
return errors.add :filename, :invalid if dst !~ /^([\w\-]+\/)*[\w\-]+(#{Regexp.escape(fix_extname)})?$/
return errors.add :base, :branch_page_can_not_move if self.try(:branch?)
return errors.add :base, :same_filename if filename == dst
return errors.add :filename, :taken if self.class.where(site_id: site_id, filename: dst).first
return errors.add :base, :exist_physical_file if Fs.exists?("#{site.path}/#{dst}")
if dst_dir.present?
dst_parent = Cms::Node.where(site_id: site_id, filename: dst_dir).first
return errors.add :base, :not_found_parent_node if dst_parent.blank?
allowed = dst_parent.allowed?(:read, @cur_user, site: @cur_site, node: @cur_node)
return errors.add :base, :not_have_parent_read_permission unless allowed
else
return errors.add :base, :not_cms_page_in_root if route != "cms/page"
end
end
def move(dst)
validate_destination_filename(dst)
if is_a?(Cms::Addon::EditLock)
errors.add :base, :locked, user: lock_owner.long_name if locked?
end
return false unless errors.empty?
@cur_node = nil
@basename = dst
if is_a?(Cms::Addon::EditLock)
remove_attribute(:lock_owner_id) if has_attribute?(:lock_owner_id)
remove_attribute(:lock_until) if has_attribute?(:lock_until)
end
save
end
private
def set_released
self.released ||= Time.zone.now
end
def fix_extname
".html"
end
module ClassMethods
def after_generate_file(method, opts = {})
callback = opts.merge(method: method)
callbacks = class_variable_get(:@@_after_generate_file_callbacks)
class_variable_set(:@@_after_generate_file_callbacks, callbacks << callback)
end
def after_remove_file(method, opts = {})
callback = opts.merge(method: method)
callbacks = class_variable_get(:@@_after_remove_file_callbacks)
class_variable_set(:@@_after_remove_file_callbacks, callbacks << callback)
end
def after_rename_file(method, opts = {})
callback = opts.merge(method: method)
callbacks = class_variable_get(:@@_after_rename_file_callbacks)
class_variable_set(:@@_after_rename_file_callbacks, callbacks << callback)
end
end
end
|
shirasagi/opendata
|
app/models/rdf/property_expander.rb
|
class Rdf::PropertyExpander
DEPTH_LIMIT = 5.freeze
def initialize(depth_limit = DEPTH_LIMIT)
@depth_limit = depth_limit
@vocab_cache = {}
@vocab_cache.default_proc = ->(hash, key) { set_vocab(hash, key) }
@class_cache = {}
@class_cache.default_proc = ->(hash, key) { set_class(hash, key) }
@props_cache = {}
@props_cache.default_proc = ->(hash, key) { set_class_props(hash, key) }
end
def with_vocab(vocab_id)
yield @vocab_cache[vocab_id]
end
def with_class(class_id)
yield @class_cache[class_id]
end
def with_props(class_id)
yield @props_cache[class_id]
end
def expand(rdf_class, depth = 0, recuirsive_super_class_check = {})
return [] if depth >= @depth_limit
ret = expand_super_class_properties(rdf_class, depth, recuirsive_super_class_check)
# check whether already flatterned.
return ret if recuirsive_super_class_check.key?(rdf_class._id)
recuirsive_super_class_check[rdf_class._id] = true
properties = @props_cache[rdf_class._id]
return ret if properties.blank?
properties.each do |prop|
prop_vocab = @vocab_cache[prop.vocab_id]
range = @class_cache[prop.range_id]
range_vocab = @vocab_cache[range.try(:vocab_id)]
tmp = range.present? ? expand(range, depth + 1) : nil
ret << [prop.id,
"#{prop_vocab.prefix}:#{prop.name}",
range.present? ? "#{range_vocab.prefix}:#{range.name}" : nil,
prop.comments.try(:preferred_value),
tmp]
end
ret
end
def flattern(rdf_class)
properties = expand(rdf_class)
return properties if properties.blank?
flattern_properties_recursive(properties)
end
private
def expand_super_class_properties(rdf_class, depth, recuirsive_super_class_check)
return [] if rdf_class.sub_class.blank?
rdf_class.sub_class.present? ? expand(rdf_class.sub_class, depth + 1, recuirsive_super_class_check) : []
end
def flattern_properties_recursive(roots)
ret = []
roots.each do |id, name, klass, comment, sub_props|
if sub_props.present?
flat_sub_props = flattern_properties_recursive(sub_props)
flat_sub_props.each do |flat_sub_prop|
flat_sub_prop[:ids].insert(0, id)
flat_sub_prop[:names].insert(0, name.split(':')[1])
flat_sub_prop[:properties].insert(0, name)
flat_sub_prop[:classes].insert(0, klass)
flat_sub_prop[:comments].insert(0, comment)
end
ret.concat(flat_sub_props)
else
ret << { ids: [id],
names: [name.split(':')[1]],
properties: [name],
classes: [klass],
comments: [comment]}
end
end
ret
end
def set_vocab(hash, vocab_id)
if vocab_id.present?
hash[vocab_id] = ::Rdf::Vocab.where(_id: vocab_id).first
end
end
def set_class(hash, class_id)
if class_id.present?
hash[class_id] = ::Rdf::Class.where(_id: class_id).first
end
end
def set_class_props(hash, class_id)
if class_id.present?
rdf_class = @class_cache[class_id] if class_id.present?
rdf_props = rdf_class.properties if rdf_class.present?
rdf_props ||= []
hash[class_id] = rdf_props.to_a if class_id.present?
end
end
end
|
shirasagi/opendata
|
app/models/concerns/cms/model/part.rb
|
<reponame>shirasagi/opendata
module Cms::Model::Part
extend ActiveSupport::Concern
extend SS::Translation
include Cms::Content
included do |mod|
store_in collection: "cms_parts"
set_permission_name "cms_parts"
field :route, type: String
field :mobile_view, type: String, default: "show"
field :ajax_view, type: String, default: "disabled"
permit_params :route, :mobile_view, :ajax_view
end
public
def route_options
Cms::Part.plugins
end
def becomes_with_route(name = nil)
super (name || route).sub("/", "/part/")
end
def mobile_view_options
[
[I18n.t('views.options.state.show'), 'show'],
[I18n.t('views.options.state.hide'), 'hide'],
]
end
def ajax_view_options
[
[I18n.t('views.options.state.enabled'), 'enabled'],
[I18n.t('views.options.state.disabled'), 'disabled'],
]
end
def ajax_html
json = url.sub(/\.html$/, ".json")
%(<a class="ss-part" data-href="#{json}">#{name}</a>)
end
private
def fix_extname
".part.html"
end
end
|
shirasagi/opendata
|
config/initializers/ss/rb_config.rb
|
#> Use RbConfig instead of obsolete and deprecated Config.
#Object.send :remove_const, :Config if defined? Object::Config
#Config = RbConfig
|
shirasagi/opendata
|
app/controllers/sys/test_controller.rb
|
<filename>app/controllers/sys/test_controller.rb<gh_stars>1-10
class Sys::TestController < ApplicationController
include Sys::BaseFilter
public
def index
redirect_to sys_test_mail_path
end
end
|
shirasagi/opendata
|
app/controllers/concerns/mobile/public_filter.rb
|
<reponame>shirasagi/opendata<filename>app/controllers/concerns/mobile/public_filter.rb<gh_stars>1-10
module Mobile::PublicFilter
extend ActiveSupport::Concern
public
def mobile_path?
filters.include?(:mobile)
end
private
def set_request_path_with_mobile
return if @cur_path !~ /^#{SS.config.mobile.location}\//
@cur_path.sub!(/^#{SS.config.mobile.location}\//, "/")
filters << :mobile
end
def render_mobile
body = response.body
# links
location = SS.config.mobile.location.gsub(/^\/|\/$/, "")
body.gsub!(/href="\/(?!#{location}\/)(?!fs\/)(.*?)"/) do
path_with_query = $1
uri = URI.parse(path_with_query)
embeds = apply_trans_sid?
embeds = false unless embeds && same_host?(uri)
if embeds
key = CGI::escapeHTML(session_key)
val = CGI::escapeHTML(mobile_session_id)
if uri.query
uri.query = "#{uri.query}&#{key}=#{val}" unless uri.query.include?("#{key}=#{val}")
else
uri.query = "#{key}=#{val}"
end
path_with_query = uri.to_s
end
"href=\"/#{location}/#{path_with_query}\""
end
body.gsub!(/<span .*?id="ss-(small|medium|large|kana|pc|mb)".*?>.*?<\/span>/, "")
# tags
body = Mobile::Converter.new(body)
body.convert!
# css
dir = "#{@cur_site.path}/css"
css = Fs.exists?("#{dir}/mobile.css") || Fs.exists?("#{dir}/mobile.scss")
css = css ? "/css/mobile.css" : "#{Rails.application.config.assets.prefix}/cms/mobile.css"
# doctype
head = []
head << %(<?xml version="1.0" encoding="UTF-8"?>)
head << %(<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">)
head << %(<html xmlns="http://www.w3.org/1999/xhtml">)
head << %(<head>)
head << %(<title>#{body.match(/<title>(.*?)<\/title>/).try(:[], 1)}</title>)
head << %(<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />)
head << %(<link rel="stylesheet" href="#{css}" />)
head << %(</head>)
body.sub!(/.*?<\/head>/m, head.join("\n"))
response.body = body.to_s
end
def session_key
unless key = Rails.application.config.session_options.merge(request.session_options || {})[:key]
key = ActionDispatch::Session::AbstractStore::DEFAULT_OPTIONS[:key]
end
key
end
def mobile_session_id
request.session_options[:id] || request.session.id
end
def same_host?(uri)
return true unless domain = uri.host
domain = "#{domain}:#{uri.port}" if uri.port
@cur_site.domains.include?(domain)
end
def apply_trans_sid?
applies = false
case SS.config.mobile.trans_sid.to_sym
when :always
applies = true
when :mobile
applies = mobile_path?
end
applies
end
end
|
shirasagi/opendata
|
spec/support/opendata/app.rb
|
<reponame>shirasagi/opendata<filename>spec/support/opendata/app.rb<gh_stars>1-10
RSpec.configuration.before(:suite) do
# override zip_dir method to write zip file to tmp dir
class Opendata::App
class << self
alias_method :zip_dir_orig, :zip_dir
@@tmp_dir = Pathname(::Dir.mktmpdir)
def zip_dir
@@tmp_dir
end
end
end
end
RSpec.configuration.after(:suite) do
FileUtils.rm_rf(Opendata::App.zip_dir)
end
|
shirasagi/opendata
|
spec/features/opendata/agents/nodes/mypage/idea/my_idea_spec.rb
|
require 'spec_helper'
describe "opendata_agents_nodes_my_idea", dbscope: :example do
let(:site) { cms_site }
let!(:node) { create_once :opendata_node_idea, name: "opendata_agents_nodes_idea" }
let!(:member) { create_once :opendata_node_member }
let!(:upper_html) { '<a href="new/">新規作成</a>' }
let!(:node_mypage) { create_once :opendata_node_mypage, filename: "mypage" }
let!(:node_myidea) { create_once :opendata_node_my_idea, filename: "#{node_mypage.filename}/idea", upper_html: upper_html }
let!(:node_login) { create :member_node_login, redirect_url: node_myidea.url }
let(:node_category_folder) { create_once(:cms_node_node, basename: "category") }
let!(:category) do
create_once(
:opendata_node_category,
name: "カテゴリー01",
filename: "#{node_category_folder.filename}/#{unique_id}",
depth: node_category_folder.depth + 1)
end
let!(:area) { create_once :opendata_node_area, name: "地域A" }
let(:node_idea) { create_once :opendata_node_idea, name: "opendata_idea" }
let!(:node_search) { create :opendata_node_search_idea }
let(:index_path) { "#{node_myidea.url}index.html" }
let(:new_path) { "#{node_myidea.url}new/" }
let(:show_path) { "#{node_myidea.url}1/" }
let(:edit_path) { "#{node_myidea.url}1/edit/" }
let(:delete_path) { "#{node_myidea.url}1/delete/" }
let(:item_name) { "アイデア01" }
let(:item_text) { "アイデア内容" }
let(:save) { "公開保存" }
let(:edit) { "編集" }
let(:delete) { "削除" }
before do
login_opendata_member(site, node_login)
end
after do
logout_opendata_member(site, node_login)
end
it "#index" do
visit "http://#{site.domain}#{index_path}"
expect(current_path).to eq index_path
end
it "#new_create_edit_delete" do
visit "http://#{site.domain}#{index_path}"
click_link "新規作成"
expect(current_path).to eq new_path
fill_in "item_name", with: item_name
fill_in "item_text", with: item_text
check category.name
click_button save
expect(current_path).to eq node_myidea.url
expect(page).to have_link(item_name)
click_link item_name
expect(current_path).to eq show_path
expect(page).to have_link(edit)
click_link edit
expect(current_path).to eq edit_path
expect(page).to have_button(save)
click_button save
expect(current_path).to eq show_path
expect(page).to have_link(delete)
click_link delete
expect(current_path).to eq delete_path
expect(page).to have_button(delete)
click_button delete
expect(current_path).to eq node_myidea.url
end
end
|
shirasagi/opendata
|
app/controllers/cms/public_controller.rb
|
class Cms::PublicController < ApplicationController
include Cms::PublicFilter
after_action :put_access_log
after_action :render_mobile, if: ->{ mobile_path? }
private
def put_access_log
#
end
end
|
shirasagi/opendata
|
app/models/opendata/dataset.rb
|
class Opendata::Dataset
include Cms::Model::Page
include ::Workflow::Addon::Approver
include Opendata::Addon::Resource
include Opendata::Addon::UrlResource
include Opendata::Addon::Category
include Opendata::Addon::Area
include Opendata::Addon::DatasetGroup
include Opendata::Reference::Member
include Opendata::Common
include Cms::Addon::Release
include Contact::Addon::Page
include Cms::Addon::RelatedPage
include Cms::Addon::GroupPermission
include Workflow::MemberPermission
set_permission_name "opendata_datasets"
scope :formast_is, ->(word, *fields) {
options = fields.extract_options!
method = options[:method].presence || 'and'
operator = method == 'and' ? "$and" : "$or"
where(operator => [{ "$or" => fields.map { |field| { field => word.to_s } } } ])
}
scope :license_is, ->(id, *fields) {
options = fields.extract_options!
method = options[:method].presence || 'and'
operator = method == 'and' ? "$and" : "$or"
where(operator => [{ "$or" => fields.map { |field| { field => id.to_i } } } ])
}
set_permission_name "opendata_datasets"
field :text, type: String
field :point, type: Integer, default: "0"
field :tags, type: SS::Extensions::Words
field :downloaded, type: Integer
has_many :points, primary_key: :dataset_id, class_name: "Opendata::DatasetPoint",
dependent: :destroy
has_many :apps, foreign_key: :dataset_ids, class_name: "Opendata::App"
has_many :ideas, foreign_key: :dataset_ids, class_name: "Opendata::Idea"
validates :text, presence: true
validates :category_ids, presence: true
permit_params :text, :tags, tags: []
before_save :seq_filename, if: ->{ basename.blank? }
after_save :on_state_changed, if: ->{ state_changed? }
default_scope ->{ where(route: "opendata/dataset") }
public
def point_url
get_url(url, "/point.html")
end
def point_members_url
get_url(url, "/point/members.html")
end
def dataset_apps_url
get_url(url, "/apps/show.html")
end
def dataset_ideas_url
get_url(url, "/ideas/show.html")
end
def contact_present?
return false if member_id.present?
super
end
private
def validate_filename
@basename.blank? ? nil : super
end
def seq_filename
self.filename = dirname ? "#{dirname}#{id}.html" : "#{id}.html"
end
def on_state_changed
resources.each do |r|
r.try(:state_changed)
end
url_resources.each do |r|
r.try(:state_changed)
end
end
class << self
public
def to_dataset_path(path)
suffix = %w(/point.html /point/members.html /apps/show.html /ideas/show.html).find { |suffix| path.end_with? suffix }
return path if suffix.blank?
path[0..(path.length - suffix.length - 1)] + '.html'
end
def sort_options
[
[I18n.t("opendata.sort_options.released"), "released"],
[I18n.t("opendata.sort_options.popular"), "popular"],
[I18n.t("opendata.sort_options.attention"), "attention"]
]
end
def sort_hash(sort)
case sort
when "released"
{ released: -1, _id: -1 }
when "popular"
{ point: -1, _id: -1 }
when "attention"
{ downloaded: -1, _id: -1 }
else
return { released: -1 } if sort.blank?
{ sort.sub(/ .*/, "") => (sort =~ /-1$/ ? -1 : 1) }
end
end
def aggregate_field(name, opts = {})
Opendata::Common.get_aggregate_field(self, name, opts)
end
def aggregate_array(name, opts = {})
Opendata::Common.get_aggregate_array(self, name, opts)
end
def aggregate_resources(name, opts = {})
Opendata::Common.get_aggregate_resources(self, name, opts)
end
def get_tag_list(query)
Opendata::Common.get_tag_list(self, query)
end
def get_tag(tag_name)
Opendata::Common.get_tag(self, tag_name)
end
def search_params
params = []
params << :keyword
params << :tag
params << :area_id
params << :category_id
params << :dataset_group
params << :format
params << :license_id
params << :option
params
end
def search_options
%w(all_keywords any_keywords any_conditions).map do |w|
[I18n.t("opendata.search_options.#{w}"), w]
end
end
def search(params)
criteria = self.where({})
return criteria if params.blank?
[ :search_keyword, :search_ids, :search_name, :search_tag, :search_area_id, :search_category_id,
:search_dataset_group, :search_format, :search_license_id, :search_poster, ].each do |m|
criteria = send(m, params, criteria)
end
criteria
end
def format_options
pipes = []
pipes << { "$match" => { "route" => "opendata/dataset" } }
pipes << { "$unwind" => "$resources" }
pipes << { "$group" => { "_id" => "$resources.format", "count" => { "$sum" => 1 } } }
self.collection.aggregate(pipes).map do |data|
format = data["_id"]
[format, format]
end
end
private
def search_keyword(params, criteria)
if params[:keyword].present?
option = params[:option].presence || 'all_keywords'
method = option == 'all_keywords' ? 'and' : 'any'
criteria = criteria.keyword_in params[:keyword],
:name, :text, "resources.name", "resources.filename", "resources.text",
"url_resources.name", "url_resources.filename", "url_resources.text",
method: method
end
criteria
end
def search_ids(params, criteria)
if params[:ids].present?
criteria = criteria.any_in id: params[:ids].split(/,/)
end
criteria
end
def search_name(params, criteria)
if params[:name].present?
if params[:modal].present?
words = params[:name].split(/[\s ]+/).uniq.compact.map {|w| /#{Regexp.escape(w)}/i }
criteria = criteria.all_in name: words
else
criteria = criteria.keyword_in params[:keyword], :name
end
end
criteria
end
def search_tag(params, criteria)
if params[:tag].present?
operator = params[:option].presence == 'any_conditions' ? "$or" : "$and"
criteria = criteria.where(operator => [ tags: params[:tag] ])
end
criteria
end
def search_area_id(params, criteria)
if params[:area_id].present?
operator = params[:option].presence == 'any_conditions' ? "$or" : "$and"
criteria = criteria.where(operator => [ area_ids: params[:area_id].to_i ])
end
criteria
end
def search_category_id(params, criteria)
return criteria if params[:category_id].blank?
category_id = params[:category_id].to_i
category_node = Cms::Node.site(params[:site]).public.where(id: category_id).first
return criteria if category_node.blank?
category_ids = [ category_id ]
category_node.all_children.public.each do |child|
category_ids << child.id
end
operator = params[:option].presence == 'any_conditions' ? "$or" : "$and"
criteria.where(operator => [ category_ids: { "$in" => category_ids } ])
end
def search_dataset_group(params, criteria)
if params[:dataset_group].present?
site = params[:site]
groups = Opendata::DatasetGroup.site(site).public.search_text(params[:dataset_group])
groups = groups.pluck(:id).presence || [-1]
operator = params[:option].presence == 'any_conditions' ? "$or" : "$and"
criteria = criteria.where(operator => [ dataset_group_ids: { "$in" => groups } ])
end
criteria
end
def search_format(params, criteria)
if params[:format].present?
option = params[:option].presence || 'all_keywords'
method = option == 'any_conditions' ? 'any' : 'and'
criteria = criteria.formast_is params[:format].upcase, "resources.format", "url_resources.format", method: method
end
criteria
end
def search_license_id(params, criteria)
if params[:license_id].present?
option = params[:option].presence || 'all_keywords'
method = option == 'any_conditions' ? 'any' : 'and'
criteria = criteria.license_is params[:license_id].to_i, "resources.license_id", "url_resources.license_id", method: method
end
criteria
end
def search_poster(params, criteria)
if params[:poster].present?
cond = {}
cond = { :workflow_member_id.exists => true } if params[:poster] == "member"
cond = { :workflow_member_id => nil } if params[:poster] == "admin"
operator = params[:option].presence == 'any_conditions' ? "$or" : "$and"
criteria = criteria.where(operator => cond)
end
criteria
end
end
end
|
shirasagi/opendata
|
db/seeds/demo/load.rb
|
Dir.chdir @root = File.dirname(__FILE__)
@site = SS::Site.find_by host: ENV["site"]
## -------------------------------------
puts "# files"
Dir.glob "files/**/*.*" do |file|
puts name = file.sub(/^files\//, "")
Fs.binwrite "#{@site.path}/#{name}", File.binread(file)
end
def save_ss_files(path, data)
puts path
cond = { site_id: @site._id, filename: data[:filename], model: data[:model] }
file = Fs::UploadedFile.create_from_file(path)
file.original_filename = data[:filename] if data[:filename].present?
item = SS::File.find_or_create_by(cond)
item.in_file = file
item.update
item
end
## -------------------------------------
puts "# layouts"
def save_layout(data)
puts data[:name]
cond = { site_id: @site._id, filename: data[:filename] }
html = File.read("layouts/" + data[:filename]) rescue nil
item = Cms::Layout.find_or_create_by(cond)
item.attributes = data.merge html: html
item.update
item.add_to_set group_ids: @site.group_ids
item
end
save_layout filename: "category-kanko.layout.html", name: "カテゴリー:観光・文化・スポーツ"
save_layout filename: "category-kenko.layout.html", name: "カテゴリー:健康・福祉"
save_layout filename: "category-kosodate.layout.html", name: "カテゴリー:子育て・教育"
save_layout filename: "category-kurashi.layout.html", name: "カテゴリー:くらし・手続き"
save_layout filename: "category-middle.layout.html", name: "カテゴリー:中間階層"
save_layout filename: "category-sangyo.layout.html", name: "カテゴリー:産業・仕事"
save_layout filename: "category-shisei.layout.html", name: "カテゴリー:市政情報"
save_layout filename: "more.layout.html", name: "記事一覧"
save_layout filename: "oshirase.layout.html", name: "お知らせ"
save_layout filename: "pages.layout.html", name: "記事レイアウト"
save_layout filename: "top.layout.html", name: "トップレイアウト"
save_layout filename: "one.layout.html", name: "1カラム"
save_layout filename: "faq-top.layout.html", name: "FAQトップ"
save_layout filename: "faq.layout.html", name: "FAQ"
save_layout filename: "event.layout.html", name: "イベントカレンダー"
save_layout filename: "map.layout.html", name: "施設ガイド"
save_layout filename: "ezine.layout.html", name: "メールマガジン"
save_layout filename: "urgency-layout/top-level1.layout.html", name: "緊急災害1:トップページ"
save_layout filename: "urgency-layout/top-level2.layout.html", name: "緊急災害2:トップページ"
save_layout filename: "urgency-layout/top-level3.layout.html", name: "緊急災害3:トップページ"
array = Cms::Layout.where(site_id: @site._id).map { |m| [m.filename.sub(/\..*/, ""), m] }
layouts = Hash[*array.flatten]
## -------------------------------------
puts "# nodes"
def save_node(data)
puts data[:name]
cond = { site_id: @site._id, filename: data[:filename] }
upper_html ||= File.read("nodes/" + data[:filename] + ".upper_html") rescue nil
loop_html ||= File.read("nodes/" + data[:filename] + ".loop_html") rescue nil
lower_html ||= File.read("nodes/" + data[:filename] + ".lower_html") rescue nil
summary_html ||= File.read("nodes/" + data[:filename] + ".summary_html") rescue nil
item = Cms::Node.unscoped.find_or_create_by(cond).becomes_with_route(data[:route])
item.upper_html = upper_html if upper_html
item.loop_html = loop_html if loop_html
item.lower_html = lower_html if lower_html
item.summary_html = summary_html if summary_html
item.attributes = data
item.update
item.add_to_set group_ids: @site.group_ids
item
end
## category
save_node route: "category/node", filename: "guide", name: "くらしのガイド"
save_node route: "category/node", filename: "kanko", name: "観光・文化・スポーツ"
save_node route: "category/node", filename: "kenko", name: "健康・福祉"
save_node route: "category/node", filename: "kosodate", name: "子育て・教育"
save_node route: "category/node", filename: "kurashi", name: "くらし・手続き", shortcut: "show"
save_node route: "category/node", filename: "kurashi/anzen", name: "交通安全・防犯"
save_node route: "category/node", filename: "kurashi/bosai", name: "防災情報"
save_node route: "category/node", filename: "kurashi/kankyo", name: "環境"
save_node route: "category/node", filename: "kurashi/koseki", name: "戸籍・印鑑登録・住民登録"
save_node route: "category/node", filename: "kurashi/nenkin", name: "年金・保険"
save_node route: "category/node", filename: "kurashi/zeikin", name: "税金"
save_node route: "category/node", filename: "sangyo", name: "産業・仕事"
save_node route: "category/node", filename: "sangyo/keiei", name: "経営支援・金融支援・企業立"
save_node route: "category/node", filename: "sangyo/nyusatsu", name: "入札・契約"
save_node route: "category/node", filename: "sangyo/shinko", name: "産業振興"
save_node route: "category/node", filename: "sangyo/todokede", name: "届出・証明・法令・規制"
save_node route: "category/node", filename: "shisei", name: "市政情報"
save_node route: "category/node", filename: "shisei/koho", name: "広報・広聴"
save_node route: "category/page", filename: "attention", name: "注目情報"
save_node route: "category/page", filename: "guide/fukushi", name: "福祉・介護"
save_node route: "category/page", filename: "guide/hikkoshi", name: "引越し・住まい"
save_node route: "category/page", filename: "guide/kekkon", name: "結婚・離婚"
save_node route: "category/page", filename: "guide/kosodate", name: "子育て"
save_node route: "category/page", filename: "guide/kyoiku", name: "教育"
save_node route: "category/page", filename: "guide/ninshin", name: "妊娠・出産"
save_node route: "category/page", filename: "guide/okuyami", name: "おくやみ"
save_node route: "category/page", filename: "guide/shushoku", name: "就職・退職"
save_node route: "category/page", filename: "kanko/bunkazai", name: "文化財"
save_node route: "category/page", filename: "kanko/geijyutsu", name: "文化・芸術"
save_node route: "category/page", filename: "kanko/kanko", name: "観光"
save_node route: "category/page", filename: "kanko/koryu", name: "国内・国際交流"
save_node route: "category/page", filename: "kanko/sports", name: "レジャー・スポーツ"
save_node route: "category/page", filename: "kenko/boshi", name: "母子保健"
save_node route: "category/page", filename: "kenko/hoken", name: "保健・健康・医療"
save_node route: "category/page", filename: "kenko/kaigo", name: "介護保険"
save_node route: "category/page", filename: "kenko/korei", name: "高齢者福祉"
save_node route: "category/page", filename: "kenko/kyukyu", name: "救急医療"
save_node route: "category/page", filename: "kenko/shogai", name: "障害福祉"
save_node route: "category/page", filename: "kenko/shokuiku", name: "食育"
save_node route: "category/page", filename: "kenko/yobo", name: "予防接種"
save_node route: "category/page", filename: "kenko/zoshin", name: "健康増進"
save_node route: "category/page", filename: "kosodate/hoikuen", name: "保育園・幼稚園"
save_node route: "category/page", filename: "kosodate/hoken", name: "母子の保健"
save_node route: "category/page", filename: "kosodate/jinken", name: "人権・平和啓発", shortcut: "show"
save_node route: "category/page", filename: "kosodate/kenko", name: "母子の健康・予防接種"
save_node route: "category/page", filename: "kosodate/kyoikuiinkai", name: "教育委員会"
save_node route: "category/page", filename: "kosodate/shien", name: "子育て支援"
save_node route: "category/page", filename: "kosodate/shogai", name: "生涯学習"
save_node route: "category/page", filename: "kosodate/shogakko", name: "小学校・中学校"
save_node route: "category/page", filename: "kosodate/sodan", name: "教育相談"
save_node route: "category/page", filename: "kurashi/anzen/bohan", name: "防犯"
save_node route: "category/page", filename: "kurashi/anzen/fushinsha", name: "不審者情報"
save_node route: "category/page", filename: "kurashi/anzen/kotsu", name: "交通安全"
save_node route: "category/page", filename: "kurashi/bosai/jyoho", name: "防災情報"
save_node route: "category/page", filename: "kurashi/bosai/kanri", name: "危機管理情報"
save_node route: "category/page", filename: "kurashi/bosai/keikaku", name: "計画"
save_node route: "category/page", filename: "kurashi/bosai/kunren", name: "防災訓練"
save_node route: "category/page", filename: "kurashi/bosai/shinsai", name: "東日本大震災"
save_node route: "category/page", filename: "kurashi/bosai/shobo", name: "消防・救急"
save_node route: "category/page", filename: "kurashi/gomi", name: "ごみ・リサイクル"
save_node route: "category/page", filename: "kurashi/kankyo/hozen", name: "環境保全"
save_node route: "category/page", filename: "kurashi/kankyo/pet", name: "愛玩動物・有害鳥獣"
save_node route: "category/page", filename: "kurashi/kankyo/seisaku", name: "環境政策"
save_node route: "category/page", filename: "kurashi/koseki/foreigner", name: "外国人住民の方へ"
save_node route: "category/page", filename: "kurashi/koseki/inkan", name: "印鑑登録"
save_node route: "category/page", filename: "kurashi/koseki/jyuki", name: "住民基本台帳・電子申請"
save_node route: "category/page", filename: "kurashi/koseki/jyumin", name: "住民登録"
save_node route: "category/page", filename: "kurashi/koseki/koseki", name: "戸籍"
save_node route: "category/page", filename: "kurashi/koseki/passport", name: "パスポート"
save_node route: "category/page", filename: "kurashi/nenkin/hoken", name: "国民健康保険"
save_node route: "category/page", filename: "kurashi/nenkin/korei", name: "高齢者医療"
save_node route: "category/page", filename: "kurashi/nenkin/nenkin", name: "国民年金"
save_node route: "category/page", filename: "kurashi/shimin", name: "市民活動"
save_node route: "category/page", filename: "kurashi/sodan", name: "相談窓口"
save_node route: "category/page", filename: "kurashi/suido", name: "上水道・下水道"
save_node route: "category/page", filename: "kurashi/sumai", name: "住まい"
save_node route: "category/page", filename: "kurashi/zeikin/kotei", name: "固定資産税"
save_node route: "category/page", filename: "kurashi/zeikin/other", name: "その他税について"
save_node route: "category/page", filename: "kurashi/zeikin/shimin", name: "市民税"
save_node route: "category/page", filename: "kurashi/zeikin/tokubetsu", name: "特別徴収"
save_node route: "category/page", filename: "kurashi/zeikin/yogo", name: "税務用語"
save_node route: "category/page", filename: "oshirase", name: "お知らせ", shortcut: "show"
save_node route: "category/page", filename: "oshirase/event", name: "イベント"
save_node route: "category/page", filename: "oshirase/kanko", name: "観光・文化・スポーツ", shortcut: "show"
save_node route: "category/page", filename: "oshirase/kenko", name: "健康・福祉", shortcut: "show"
save_node route: "category/page", filename: "oshirase/kosodate", name: "子育て・教育", shortcut: "show"
save_node route: "category/page", filename: "oshirase/kurashi", name: "くらし・手続き", shortcut: "show"
save_node route: "category/page", filename: "oshirase/sangyo", name: "産業・仕事", shortcut: "show"
save_node route: "category/page", filename: "oshirase/shisei", name: "市政情報", shortcut: "show"
save_node route: "category/page", filename: "sangyo/jinzai", name: "人材募集"
save_node route: "category/page", filename: "sangyo/keiei/hojo", name: "補助・助成"
save_node route: "category/page", filename: "sangyo/keiei/keiei", name: "経営支援"
save_node route: "category/page", filename: "sangyo/keiei/kigyo", name: "企業支援"
save_node route: "category/page", filename: "sangyo/keiei/kinyu", name: "金融支援"
save_node route: "category/page", filename: "sangyo/keiei/ricchi", name: "企業立地"
save_node route: "category/page", filename: "sangyo/nyusatsu/buppin", name: "物品・業務委託等"
save_node route: "category/page", filename: "sangyo/nyusatsu/kobai", name: "公売・市有地売却"
save_node route: "category/page", filename: "sangyo/nyusatsu/koji", name: "工事"
save_node route: "category/page", filename: "sangyo/nyusatsu/kokoku", name: "入札・企画提案の公告"
save_node route: "category/page", filename: "sangyo/nyusatsu/tokutei", name: "特定調達契約情報"
save_node route: "category/page", filename: "sangyo/shinko/kaigai", name: "海外ビジネス支援"
save_node route: "category/page", filename: "sangyo/shinko/norinsuisan", name: "農林水産業"
save_node route: "category/page", filename: "sangyo/shinko/sangakukan", name: "産学官連携"
save_node route: "category/page", filename: "sangyo/shinko/shoko", name: "商工業"
save_node route: "category/page", filename: "sangyo/shinko/shotengai", name: "商店街"
save_node route: "category/page", filename: "sangyo/shitei", name: "指定管理者制度"
save_node route: "category/page", filename: "sangyo/shuro", name: "就労支援"
save_node route: "category/page", filename: "sangyo/todokede/kaigo", name: "介護・福祉"
save_node route: "category/page", filename: "sangyo/todokede/kankyo", name: "環境・ごみ・リサイクル"
save_node route: "category/page", filename: "sangyo/todokede/kenchiku", name: "建築・土地・開発・景観"
save_node route: "category/page", filename: "sangyo/todokede/kenko", name: "健康・医療"
save_node route: "category/page", filename: "sangyo/todokede/kosodate", name: "子育て"
save_node route: "category/page", filename: "sangyo/todokede/norinsuisan", name: "農林水産業"
save_node route: "category/page", filename: "sangyo/todokede/shobo", name: "消防・救急"
save_node route: "category/page", filename: "sangyo/todokede/shoko", name: "商工業"
save_node route: "category/page", filename: "sangyo/todokede/shokuhin", name: "食品・衛生"
save_node route: "category/page", filename: "sangyo/zeikin", name: "企業の税金"
save_node route: "category/page", filename: "shisei/chosha", name: "庁舎案内"
save_node route: "category/page", filename: "shisei/gaiyo", name: "市の概要"
save_node route: "category/page", filename: "shisei/jinji", name: "人事・職員募集"
save_node route: "category/page", filename: "shisei/koho/pamphlet", name: "パンフレット"
save_node route: "category/page", filename: "shisei/koho/shirasagi", name: "広報SHIRASAGI"
save_node route: "category/page", filename: "shisei/koho/shiryo", name: "報道発表資料"
save_node route: "category/page", filename: "shisei/senkyo", name: "選挙"
save_node route: "category/page", filename: "shisei/shicho", name: "市長の部屋"
save_node route: "category/page", filename: "shisei/shisaku", name: "施策・計画"
save_node route: "category/node", filename: "shisei/soshiki", name: "組織案内"
save_node route: "category/node", filename: "shisei/soshiki/kikaku", name: "企画政策部", order: 10
save_node route: "category/node", filename: "shisei/soshiki/soumu", name: "総務部", order: 20
save_node route: "category/node", filename: "shisei/soshiki/keizai", name: "経済部", order: 30
save_node route: "category/node", filename: "shisei/soshiki/kensetu", name: "建設部", order: 40
save_node route: "category/node", filename: "shisei/soshiki/kikikanri", name: "危機管理部", order: 50
save_node route: "category/node", filename: "shisei/soshiki/kyoiku", name: "教育委員会", order: 60
save_node route: "category/page", filename: "shisei/soshiki/kikaku/koho", name: "広報課", order: 10
save_node route: "category/page", filename: "shisei/soshiki/kikaku/seisaku", name: "政策課", order: 20
save_node route: "category/page", filename: "shisei/soshiki/kikaku/hisho", name: "秘書課", order: 30
save_node route: "category/page", filename: "shisei/soshiki/soumu/somu", name: "総務課", order: 10
save_node route: "category/page", filename: "shisei/soshiki/soumu/shokuin", name: "職員課", order: 20
save_node route: "category/page", filename: "shisei/soshiki/soumu/nouzei", name: "納税課", order: 30
save_node route: "category/page", filename: "shisei/toke", name: "統計・人口"
save_node route: "category/page", filename: "shisei/toshi", name: "都市整備"
save_node route: "category/page", filename: "shisei/zaisei", name: "財政・行政改革"
save_node route: "category/page", filename: "urgency", name: "緊急情報", shortcut: "show"
save_node route: "category/node", filename: "faq", name: "よくある質問", shortcut: "show", sort: "order"
save_node route: "category/page", filename: "faq/kurashi", name: "くらし・手続き", order: 10
save_node route: "category/page", filename: "faq/kosodate", name: "子育て・教育", order: 20
save_node route: "category/page", filename: "faq/kenko", name: "健康・福祉", order: 30
save_node route: "category/page", filename: "faq/kanko", name: "観光・文化・スポーツ", order: 40
save_node route: "category/page", filename: "faq/sangyo", name: "産業・仕事", order: 50
save_node route: "category/page", filename: "faq/shisei", name: "市政情報", order: 60
save_node route: "category/page", filename: "calendar/bunka", name: "文化・芸術", order: 10
save_node route: "category/page", filename: "calendar/kohen", name: "講演・講座", order: 20
save_node route: "category/page", filename: "calendar/sports", name: "スポーツ", order: 60
array = Category::Node::Base.where(site_id: @site._id).map { |m| [m.filename, m] }
categories = Hash[*array.flatten]
## node
save_node route: "cms/node", filename: "use", name: "ご利用案内"
## article
save_node route: "article/page", filename: "docs", name: "記事", shortcut: "show"
## sitemap
save_node route: "sitemap/page", filename: "sitemap", name: "サイトマップ"
## event
save_node route: "event/page", filename: "calendar", name: "イベントカレンダー", conditions: %w(docs),
st_category_ids: %w(calendar/bunka calendar/kohen calendar/sports).map{ |c| categories[c].id }
## uploader
save_node route: "uploader/file", filename: "css", name: "CSS", shortcut: "show"
save_node route: "uploader/file", filename: "img", name: "画像", shortcut: "show"
save_node route: "uploader/file", filename: "js", name: "javascript", shortcut: "show"
## faq
save_node route: "faq/page", filename: "faq/docs", name: "よくある質問記事", st_category_ids: [categories["faq"].id]
save_node route: "faq/search", filename: "faq/faq-search", name: "よくある質問検索", st_category_ids: [categories["faq"].id]
## ads
save_node route: "ads/banner", filename: "add", name: "広告バナー", shortcut: "show"
## urgency
save_node route: "urgency/layout", filename: "urgency-layout", name: "緊急災害レイアウト",
urgency_default_layout_id: layouts["top"].id, shortcut: "show"
## inquiry
inquiry_html = File.read("nodes/inquiry.inquiry_html") rescue nil
inquiry_sent_html = File.read("nodes/inquiry.inquiry_sent_html") rescue nil
inquiry_node = save_node route: "inquiry/form", filename: "inquiry", name: "市へのお問い合わせ", shortcut: "show",
from_name: "シラサギサンプルサイト",
inquiry_captcha: "enabled", notice_state: "disabled",
inquiry_html: inquiry_html, inquiry_sent_html: inquiry_sent_html,
reply_state: "disabled",
reply_subject: "シラサギ市へのお問い合わせを受け付けました。",
reply_upper_text: "以下の内容でお問い合わせを受け付けました。",
reply_lower_text: "以上。",
aggregation_state: "disabled"
## public comment
save_node route: "inquiry/node", filename: "comment", name: "パブリックコメント", upper_html: "パブリックコメント一覧です。"
inquiry_comment_1 = save_node route: "inquiry/form", filename: "comment/comment01", name: "シラサギ市政について",
from_name: "シラサギサンプルサイト",
inquiry_captcha: "enabled", notice_state: "disabled",
inquiry_html: inquiry_html,
inquiry_sent_html: "<p>パブリックコメントを受け付けました。</p>",
reply_state: "disabled",
reply_subject: "シラサギ市へのお問い合わせを受け付けました。",
reply_upper_text: "以下の内容でお問い合わせを受け付けました。",
reply_lower_text: "以上。",
aggregation_state: "enabled",
reception_start_date: Time.zone.now.beginning_of_month,
reception_close_date: Time.zone.now.end_of_month
inquiry_comment_2 = save_node route: "inquiry/form", filename: "comment/comment02", name: "シラサギ市都市計画について",
from_name: "シラサギサンプルサイト",
inquiry_captcha: "enabled", notice_state: "disabled",
inquiry_html: inquiry_html,
inquiry_sent_html: "<p>パブリックコメントを受け付けました。</p>",
reply_state: "disabled",
reply_subject: "シラサギ市へのお問い合わせを受け付けました。",
reply_upper_text: "以下の内容でお問い合わせを受け付けました。",
reply_lower_text: "以上。",
aggregation_state: "enabled",
reception_start_date: Time.zone.now.prev_month.beginning_of_month,
reception_close_date: Time.zone.now.prev_month.end_of_month
## ezine
def save_ezine_column(data)
puts data[:name]
cond = { site_id: data[:site_id], node_id: data[:node_id], name: data[:name] }
item = Ezine::Column.find_or_create_by(cond)
item.attributes = data
item.update
item
end
ezine_signature_html = File.read("nodes/ezine.signature_html") rescue nil
ezine_signature_text = File.read("nodes/ezine.signature_text") rescue nil
ezine_reply_signature = File.read("nodes/ezine.reply_signature") rescue nil
ezine_page_node = save_node route: "ezine/page", filename: "ezine", name: "メールマガジン",
sender_name: "シラサギサンプルサイト",
sender_email: "<EMAIL>",
reply_upper_text: "メールマガジン登録を受け付けました。",
signature_html: ezine_signature_html,
signature_text: ezine_signature_text,
reply_signature: ezine_reply_signature
ezine_backnumber_node = save_node route: "ezine/backnumber", filename: "ezine/backnumber",
name: "メールマガジン バックナンバー", conditions: %w(ezine)
save_ezine_column node_id: ezine_page_node.id, name: "性別", order: 0, input_type: "radio_button",
select_options: %w(男性 女性), required: "required", site_id: @site._id
## facility
save_node route: "cms/node", filename: "institution/chiki", name: "施設のある地域", layout_id: layouts["one"].id
center_point = Map::Extensions::Point.mongoize(loc: [34.075593, 134.550614], zoom_level: 10)
save_node route: "facility/location", filename: "institution/chiki/higashii",
name: "東区", order: 10, center_point: center_point
center_point = Map::Extensions::Point.mongoize(loc: [34.034417, 133.808902], zoom_level: 10)
save_node route: "facility/location", filename: "institution/chiki/nishi",
name: "西区", order: 20, center_point: center_point
center_point = Map::Extensions::Point.mongoize(loc: [33.609123, 134.352387], zoom_level: 10)
save_node route: "facility/location", filename: "institution/chiki/minami",
name: "南区", order: 30, center_point: center_point
center_point = Map::Extensions::Point.mongoize(loc: [34.179472, 134.608579], zoom_level: 10)
save_node route: "facility/location", filename: "institution/chiki/kita",
name: "北区", order: 40, center_point: center_point
save_node route: "cms/node", filename: "institution/shurui", name: "施設の種類", layout_id: layouts["one"].id
save_node route: "facility/category", filename: "institution/shurui/bunka", name: "文化施設", order: 10
save_node route: "facility/category", filename: "institution/shurui/sports", name: "運動施設", order: 20
save_node route: "facility/category", filename: "institution/shurui/school", name: "小学校", order: 30
save_node route: "facility/category", filename: "institution/shurui/kokyo", name: "公園・公共施設", order: 40
save_node route: "cms/node", filename: "institution/yoto", name: "施設の用途", layout_id: layouts["one"].id
save_node route: "facility/service", filename: "institution/yoto/asobu", name: "遊ぶ", order: 10
save_node route: "facility/service", filename: "institution/yoto/manabu", name: "学ぶ", order: 20
save_node route: "facility/service", filename: "institution/yoto/sodan", name: "相談する", order: 30
array = Facility::Node::Category.where(site_id: @site._id).map { |m| [m.filename, m] }
facility_categories = Hash[*array.flatten]
array = Facility::Node::Location.where(site_id: @site._id).map { |m| [m.filename, m] }
facility_locations = Hash[*array.flatten]
array = Facility::Node::Service.where(site_id: @site._id).map { |m| [m.filename, m] }
facility_services = Hash[*array.flatten]
save_node route: "facility/search", filename: "institution", name: "施設ガイド",
st_category_ids: facility_categories.values.map{ |cate| cate.id },
st_location_ids: facility_locations.values.map{ |loc| loc.id },
st_service_ids: facility_services.values.map{ |serv| serv.id }
save_node route: "facility/node", filename: "institution/shisetsu", name: "施設一覧",
st_category_ids: facility_categories.values.map{ |cate| cate.id },
st_location_ids: facility_locations.values.map{ |loc| loc.id },
st_service_ids: facility_services.values.map{ |serv| serv.id }
save_node route: "facility/page", filename: "institution/shisetsu/library", name: "シラサギ市立図書館",
kana: "しらさぎとしょかん",
address: "大鷺県シラサギ市小鷺町1丁目1番地1号",
tel: "00-0000-0000",
fax: "00-0000-0000",
related_url: "http://demo.ss-proj.org/",
category_ids: facility_categories.values.map(&:id),
location_ids: facility_locations.values.map(&:id),
service_ids: facility_services.values.map(&:id)
save_node route: "key_visual/image", filename: "key_visual", name: "キービジュアル"
## inquiry
def save_inquiry_column(data)
puts data[:name]
cond = { site_id: data[:site_id], node_id: data[:node_id], name: data[:name] }
item = Inquiry::Column.find_or_create_by(cond)
item.attributes = data
item.update
item
end
def save_inquiry_answer(data)
item = Inquiry::Answer.new
item.set_data(data[:data])
data.delete(:data)
item.attributes = data
raise item.errors.full_messages.to_s unless item.save
item
end
puts "# inquiry"
column_name_html = File.read("columns/name.html") rescue nil
column_company_html = File.read("columns/company.html") rescue nil
column_email_html = File.read("columns/email.html") rescue nil
column_gender_html = File.read("columns/gender.html") rescue nil
column_age_html = File.read("columns/age.html") rescue nil
column_category_html = File.read("columns/category.html") rescue nil
column_question_html = File.read("columns/question.html") rescue nil
save_inquiry_column node_id: inquiry_node.id, name: "お名前", order: 0, input_type: "text_field",
html: column_name_html, select_options: [], required: "required", site_id: @site._id
save_inquiry_column node_id: inquiry_node.id, name: "企業・団体名", order: 10, input_type: "text_field",
html: column_company_html, select_options: [], required: "optional", site_id: @site._id
save_inquiry_column node_id: inquiry_node.id, name: "メールアドレス", order: 20, input_type: "email_field",
html: column_email_html, select_options: [], required: "required", input_confirm: "enabled", site_id: @site._id
save_inquiry_column node_id: inquiry_node.id, name: "性別", order: 30, input_type: "radio_button",
html: column_gender_html, select_options: %w(男性 女性), required: "required", site_id: @site._id
save_inquiry_column node_id: inquiry_node.id, name: "年齢", order: 40, input_type: "select",
html: column_age_html, select_options: %w(10代 20代 30代 40代 50代 60代 70代 80代), required: "required", site_id: @site._id
save_inquiry_column node_id: inquiry_node.id, name: "お問い合わせ区分", order: 50, input_type: "check_box",
html: column_category_html, select_options: %w(市政について ご意見・ご要望 申請について その他), required: "required", site_id: @site._id
save_inquiry_column node_id: inquiry_node.id, name: "お問い合わせ内容", order: 60, input_type: "text_area",
html: column_question_html, select_options: [], required: "required", site_id: @site._id
puts "# inquiry public comment"
save_inquiry_column node_id: inquiry_comment_1.id, name: "性別", order: 0, input_type: "radio_button",
html: column_gender_html, select_options: %w(男性 女性), required: "required", site_id: @site._id
save_inquiry_column node_id: inquiry_comment_1.id, name: "年齢", order: 10, input_type: "select",
html: column_age_html, select_options: %w(10代 20代 30代 40代 50代 60代 70代 80代), required: "required", site_id: @site._id
save_inquiry_column node_id: inquiry_comment_1.id, name: "意見", order: 20, input_type: "text_area",
html: "<p>ご意見を入力してください。</p>", select_options: [], required: "required", site_id: @site._id
column_gender = save_inquiry_column node_id: inquiry_comment_2.id, name: "性別", order: 0, input_type: "radio_button",
html: column_gender_html, select_options: %w(男性 女性), required: "required", site_id: @site._id
column_age = save_inquiry_column node_id: inquiry_comment_2.id, name: "年齢", order: 10, input_type: "select",
html: column_age_html, select_options: %w(10代 20代 30代 40代 50代 60代 70代 80代), required: "required", site_id: @site._id
column_opinion = save_inquiry_column node_id: inquiry_comment_2.id, name: "意見", order: 20, input_type: "text_area",
html: "<p>ご意見を入力してください。</p>", select_options: [], required: "required", site_id: @site._id
save_inquiry_answer node_id: inquiry_comment_2.id, site_id: @site._id,
remote_addr: "192.0.2.0", user_agent: "dummy connection (input by seed demo)",
data: {
column_gender.id => "女性",
column_age.id => "10代",
column_opinion.id => "意見があります。"
}
save_inquiry_answer node_id: inquiry_comment_2.id, site_id: @site._id,
remote_addr: "192.0.2.0", user_agent: "dummy connection (input by seed demo)",
data: {
column_gender.id => "女性",
column_age.id => "80代",
column_opinion.id => "意見があります。"
}
save_inquiry_answer node_id: inquiry_comment_2.id, site_id: @site._id,
remote_addr: "192.0.2.0", user_agent: "dummy connection (input by seed demo)",
data: {
column_gender.id => "男性",
column_age.id => "50代",
column_opinion.id => "意見があります。"
}
save_inquiry_answer node_id: inquiry_comment_2.id, site_id: @site._id,
remote_addr: "192.0.2.0", user_agent: "dummy connection (input by seed demo)",
data: {
column_gender.id => "男性",
column_age.id => "10代",
column_opinion.id => "意見があります。"
}
## layout
Cms::Node.where(site_id: @site._id, route: /^article\//).update_all(layout_id: layouts["pages"].id)
Cms::Node.where(site_id: @site._id, route: /^event\//).update_all(layout_id: layouts["event"].id)
Cms::Node.where(site_id: @site._id, route: /^category\//, filename: "oshirase").
update_all(layout_id: layouts["more"].id)
Cms::Node.where(site_id: @site._id, route: /^category\//, filename: "kanko").
update_all(layout_id: layouts["category-kanko"].id)
Cms::Node.where(site_id: @site._id, route: /^category\//, filename: "kenko").
update_all(layout_id: layouts["category-kenko"].id)
Cms::Node.where(site_id: @site._id, route: /^category\//, filename: "kosodate").
update_all(layout_id: layouts["category-kosodate"].id)
Cms::Node.where(site_id: @site._id, route: /^category\//, filename: "kurashi").
update_all(layout_id: layouts["category-kurashi"].id)
Cms::Node.where(site_id: @site._id, route: /^category\//, filename: "guide").
update_all(layout_id: layouts["category-middle"].id)
Cms::Node.where(site_id: @site._id, route: /^category\//, filename: "sangyo").
update_all(layout_id: layouts["category-sangyo"].id)
Cms::Node.where(site_id: @site._id, route: /^category\//, filename: "shisei").
update_all(layout_id: layouts["category-shisei"].id)
Cms::Node.where(site_id: @site._id, route: /^category\//, filename: "attention").
update_all(layout_id: layouts["category-shisei"].id)
Cms::Node.where(site_id: @site._id, route: /^category\//, filename: /\//).
update_all(layout_id: layouts["category-middle"].id)
Cms::Node.where(site_id: @site._id, route: /^category\//, filename: /^oshirase\//).
update_all(layout_id: layouts["more"].id)
Cms::Node.where(site_id: @site._id, route: /^category\//, filename: "urgency").
update_all(layout_id: layouts["more"].id)
Cms::Node.where(site_id: @site._id, route: /^inquiry\//).
update_all(layout_id: layouts["one"].id)
Cms::Node.where(site_id: @site._id, filename: /^sitemap$/).
update_all(layout_id: layouts["one"].id)
Cms::Node.where(site_id: @site._id, filename: /^faq$/).
update_all(layout_id: layouts["faq-top"].id)
Cms::Node.where(site_id: @site._id, filename: /^add$/).
update_all(layout_id: layouts["one"].id)
Cms::Node.where(site_id: @site._id, filename: /faq\//).
update_all(layout_id: layouts["faq"].id)
Cms::Node.where(site_id: @site._id, route: /facility\//).
update_all(layout_id: layouts["map"].id)
Cms::Node.where(site_id: @site._id, route: /ezine\//).
update_all(layout_id: layouts["ezine"].id)
## -------------------------------------
puts "# parts"
def save_part(data)
puts data[:name]
cond = { site_id: @site._id, filename: data[:filename] }
html = File.read("parts/" + data[:filename]) rescue nil
upper_html ||= File.read("parts/" + data[:filename].sub(/\.html$/, ".upper_html")) rescue nil
loop_html ||= File.read("parts/" + data[:filename].sub(/\.html$/, ".loop_html")) rescue nil
lower_html ||= File.read("parts/" + data[:filename].sub(/\.html$/, ".lower_html")) rescue nil
item = Cms::Part.unscoped.find_or_create_by(cond).becomes_with_route(data[:route])
item.html = html if html
item.upper_html = upper_html if upper_html
item.loop_html = loop_html if loop_html
item.lower_html = lower_html if lower_html
item.attributes = data
item.update
item.add_to_set group_ids: @site.group_ids
item
end
save_part route: "cms/free", filename: "about.part.html", name: "シラサギ市について"
save_part route: "cms/free", filename: "foot.part.html", name: "フッター"
save_part route: "cms/free", filename: "guide.part.html", name: "くらしのガイド"
save_part route: "cms/free", filename: "head.part.html", name: "ヘッダー"
save_part route: "cms/free", filename: "keyvisual.part.html", name: "キービジュアル", mobile_view: "hide"
save_part route: "cms/free", filename: "links-life.part.html", name: "関連リンク:くらし・手続き"
save_part route: "cms/free", filename: "navi.part.html", name: "グローバルナビ"
save_part route: "cms/free", filename: "online.part.html", name: "オンラインサービス"
save_part route: "cms/free", filename: "connect.part.html", name: "関連サイト", mobile_view: "hide"
save_part route: "cms/free", filename: "page-top.part.html", name: "ページトップ"
save_part route: "cms/free", filename: "population.part.html", name: "人口・世帯数", mobile_view: "hide"
save_part route: "cms/free", filename: "propose.part.html", name: "ご意見・ご提案"
save_part route: "cms/free", filename: "ranking.part.html", name: "アクセスランキング", mobile_view: "hide"
save_part route: "cms/free", filename: "relations.part.html", name: "広報"
save_part route: "cms/free", filename: "safety.part.html", name: "安心安全情報"
save_part route: "cms/free", filename: "tool.part.html", name: "アクセシビリティーツール", mobile_view: "hide"
save_part route: "cms/free", filename: "topics.part.html", name: "街の話題"
save_part route: "cms/free", filename: "useful.part.html", name: "お役立ち情報"
save_part route: "cms/free", filename: "map-side.part.html", name: "サイドメニュー:施設ガイド"
save_part route: "cms/free", filename: "ezine-side.part.html", name: "サイドメニュー:メールマガジン"
save_part route: "article/page", filename: "attention/recent.part.html", name: "注目情報", limit: 5
save_part route: "article/page", filename: "docs/recent.part.html", name: "新着情報"
save_part route: "article/page", filename: "oshirase/kanko/recent.part.html", name: "お知らせ", limit: 6
save_part route: "article/page", filename: "oshirase/kenko/recent.part.html", name: "お知らせ", limit: 5
save_part route: "article/page", filename: "oshirase/kosodate/recent.part.html", name: "お知らせ", limit: 5
save_part route: "article/page", filename: "oshirase/kurashi/recent.part.html", name: "お知らせ", limit: 5
save_part route: "article/page", filename: "oshirase/recent.part.html", name: "お知らせ", limit: 5
save_part route: "article/page", filename: "oshirase/sangyo/recent.part.html", name: "お知らせ", limit: 5
save_part route: "article/page", filename: "oshirase/shisei/recent.part.html", name: "お知らせ", limit: 5
save_part route: "cms/crumb", filename: "breadcrumb.part.html", name: "パンくず", mobile_view: "hide"
save_part route: "category/node", filename: "category-list.part.html", name: "カテゴリーリスト", limit: 20, sort: "order"
save_part route: "cms/tabs", filename: "recent-tabs.part.html", name: "新着タブ",
conditions: %w(oshirase oshirase/event shisei/jinji), limit: 6
save_part route: "cms/free", filename: "urgency-layout/announce.part.html", name: "緊急アナウンス"
save_part route: "cms/free", filename: "urgency-layout/calamity.part.html", name: "災害関係ホームページ"
save_part route: "cms/free", filename: "urgency-layout/connect.part.html", name: "関連サイト"
save_part route: "cms/free", filename: "urgency-layout/head.part.html", name: "ヘッダー"
save_part route: "cms/free", filename: "urgency-layout/mode.part.html", name: "緊急災害表示"
save_part route: "cms/free", filename: "urgency-layout/navi.part.html", name: "グローバルナビ"
save_part route: "article/page", filename: "urgency/recent.part.html", name: "緊急情報", limit: 20
save_part route: "category/node", filename: "faq/category-list.part.html", name: "カテゴリーリスト", sort: "order"
save_part route: "faq/search", filename: "faq/faq-search/search.part.html", name: "FAQ記事検索"
save_part route: "event/calendar", filename: "calendar/calendar.part.html", name: "カレンダー", ajax_view: "enabled"
save_part route: "ads/banner", filename: "add/add.part.html", name: "広告バナー", mobile_view: "hide"
save_part route: "cms/sns_share", filename: "sns.part.html", name: "sns", mobile_view: "hide"
save_part route: "key_visual/slide", filename: "key_visual/slide.part.html", name: "スライドショー", mobile_view: "hide"
## -------------------------------------
def save_page(data)
puts data[:name]
cond = { site_id: @site._id, filename: data[:filename] }
html ||= File.read("pages/" + data[:filename]) rescue nil
summary_html ||= File.read("pages/" + data[:filename].sub(/\.html$/, "") + ".summary_html") rescue nil
item = Cms::Page.find_or_create_by(cond).becomes_with_route(data[:route])
item.html = html if html
item.summary_html = summary_html if summary_html
item.attributes = data
item.update
item.add_to_set group_ids: @site.group_ids
item
end
## -------------------------------------
puts "# articles"
contact_group = SS::Group.where(name: "シラサギ市/企画政策部/政策課").first
contact_group_id = contact_group.id rescue nil
contact_email = contact_group_id ? "<EMAIL>" : nil
contact_tel = contact_group_id ? "000-000-0000" : nil
contact_fax = contact_group_id ? "000-000-0000" : nil
save_page route: "article/page", filename: "docs/1.html", name: "インフルエンザによる学級閉鎖状況",
layout_id: layouts["pages"].id, category_ids: [categories["attention"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/2.html", name: "コンビニ納付のお知らせ",
layout_id: layouts["oshirase"].id,
category_ids: [ categories["attention"].id,
categories["shisei/soshiki"].id,
categories["shisei/soshiki/kikaku"].id,
categories["shisei/soshiki/kikaku/koho"].id,
categories["shisei/soshiki/kikaku/seisaku"].id,
categories["shisei/soshiki/soumu"].id,
categories["shisei/soshiki/soumu/nouzei"].id
],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/3.html", name: "平成26年第1回シラサギ市議会定例会を開催します",
layout_id: layouts["oshirase"].id, category_ids: [categories["attention"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/4.html", name: "放射性物質・震災関連情報",
layout_id: layouts["oshirase"].id, category_ids: [categories["attention"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/5.html", name: "市内の微小粒子状物質(PM2.5)の測定データ(速報値)を公開しています。",
layout_id: layouts["oshirase"].id, category_ids: [categories["attention"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/7.html", name: "還付金詐欺と思われる不審な電話にご注意ください",
layout_id: layouts["oshirase"].id,
category_ids: [ categories["oshirase"].id,
categories["shisei/soshiki"].id,
categories["shisei/soshiki/kikaku"].id,
categories["shisei/soshiki/kikaku/koho"].id,
categories["shisei/soshiki/kikaku/seisaku"].id,
],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/8.html", name: "平成26年度 シラサギ市システム構築に係るの公募型企画競争",
layout_id: layouts["oshirase"].id,
category_ids: [ categories["oshirase"].id,
categories["shisei/soshiki"].id,
categories["shisei/soshiki/kikaku"].id,
categories["shisei/soshiki/kikaku/koho"].id,
categories["shisei/soshiki/kikaku/seisaku"].id,
],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/9.html", name: "冬の感染症に備えましょう",
layout_id: layouts["oshirase"].id, category_ids: [categories["oshirase"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/11.html", name: "広報SHIRASAGI3月号を掲載",
layout_id: layouts["oshirase"].id,
category_ids: [ categories["oshirase"].id,
categories["oshirase/kurashi"].id,
categories["shisei/soshiki"].id,
categories["shisei/soshiki/kikaku"].id,
categories["shisei/soshiki/kikaku/koho"].id,
],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/12.html", name: "インフルエンザ流行警報がでています",
layout_id: layouts["oshirase"].id, category_ids: [categories["oshirase"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/14.html", name: "転出届",
layout_id: layouts["pages"].id, category_ids: [categories["kurashi/koseki/jyumin"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/15.html", name: "転入届",
layout_id: layouts["pages"].id, category_ids: [categories["kurashi/koseki/jyumin"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/16.html", name: "世帯または世帯主を変更するとき",
layout_id: layouts["pages"].id, category_ids: [categories["kurashi/koseki/jyumin"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/17.html", name: "証明書発行窓口",
layout_id: layouts["pages"].id, category_ids: [categories["kurashi/koseki/jyumin"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/18.html", name: "住民票記載事項証明書様式",
layout_id: layouts["pages"].id, category_ids: [categories["kurashi/koseki/jyumin"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/19.html", name: "住所変更の証明書について",
layout_id: layouts["pages"].id, category_ids: [categories["kurashi/koseki/jyumin"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/20.html", name: "住民票コードとは",
layout_id: layouts["pages"].id, category_ids: [categories["kurashi/koseki/jyumin"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/21.html", name: "住民票コードの変更",
layout_id: layouts["pages"].id, category_ids: [categories["kurashi/koseki/jyumin"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/22.html", name: "自動交付機・コンビニ交付サービスについて",
layout_id: layouts["pages"].id,
category_ids: [ categories["oshirase"].id,
categories["oshirase/kurashi"].id,
categories["shisei/soshiki"].id,
categories["shisei/soshiki/kikaku"].id,
categories["shisei/soshiki/kikaku/koho"].id,
categories["shisei/soshiki/kikaku/seisaku"].id,
],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "docs/tenkyo.html", name: "転居届",
layout_id: layouts["pages"].id, category_ids: [categories["kurashi/koseki/jyumin"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "oshirase/kurashi/23.html", name: "犬・猫を譲り受けたい方",
layout_id: layouts["oshirase"].id, category_ids: [categories["oshirase"].id, categories["oshirase/kurashi"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "oshirase/kurashi/24.html", name: "平成26年度住宅補助金の募集について掲載しました。",
layout_id: layouts["oshirase"].id, category_ids: [categories["oshirase"].id, categories["oshirase/kurashi"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "oshirase/kurashi/25.html", name: "休日臨時窓口を開設します。",
layout_id: layouts["oshirase"].id,
category_ids: [ categories["oshirase"].id,
categories["oshirase/kurashi"].id,
categories["shisei/soshiki"].id,
categories["shisei/soshiki/kikaku"].id,
categories["shisei/soshiki/kikaku/koho"].id,
categories["shisei/soshiki/kikaku/seisaku"].id,
],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "oshirase/kurashi/26.html", name: "身体障害者手帳の認定基準が変更",
layout_id: layouts["oshirase"].id, category_ids: [categories["oshirase"].id, categories["oshirase/kurashi"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "oshirase/kurashi/27.html", name: "平成26年4月より国民健康保険税率が改正されます",
layout_id: layouts["oshirase"].id,
category_ids: [ categories["oshirase"].id,
categories["oshirase/kurashi"].id,
categories["shisei/soshiki/soumu"].id,
categories["shisei/soshiki/soumu/nouzei"].id
],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "urgency/28.html", name: "黒鷺県沖で発生した地震による当市への影響について。",
layout_id: layouts["oshirase"].id, category_ids: [categories["urgency"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
save_page route: "article/page", filename: "urgency/29.html", name: "黒鷺県沖で発生した地震による津波被害について。",
layout_id: layouts["more"].id, category_ids: [categories["urgency"].id],
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
file = save_ss_files "ss_files/article/pdf_file.pdf", filename: "pdf_file.pdf", model: "article/page"
save_page route: "article/page", filename: "docs/30.html", name: "ふれあいフェスティバル",
layout_id: layouts["oshirase"].id,
category_ids: [ categories["oshirase"].id,
categories["oshirase/event"].id,
categories["shisei/soshiki"].id,
categories["shisei/soshiki/kikaku"].id,
categories["shisei/soshiki/kikaku/koho"].id,
],
file_ids: [file.id],
html: '<p><a class="icon-pdf" href="' + file.url + '">サンプルファイル (PDF 783KB)</a></p>',
contact_group_id: contact_group_id, contact_email: contact_email, contact_tel: contact_tel, contact_fax: contact_fax
dates = (Time.zone.today..(Time.zone.today + 20)).map { |d| d.mongoize }
save_page route: "event/page", filename: "calendar/31.html", name: "住民相談会を開催します。",
layout_id: layouts["event"].id, category_ids: [categories["calendar/kohen"].id], event_dates: dates,
schedule: "〇〇年○月〇日", venue: "○○○○○○○○○○", cost: "○○○○○○○○○○",
content: "○○○○○○○○○○○○○○○○○○○○", related_url: "http://demo.ss-proj.org/"
## -------------------------------------
puts "sitemap"
sitemap_urls = File.read("sitemap/urls.txt") rescue nil
save_page route: "sitemap/page", filename: "sitemap/index.html", name: "サイトマップ",
layout_id: layouts["one"].id, sitemap_urls: sitemap_urls
## -------------------------------------
puts "# faq"
save_page route: "faq/page", filename: "faq/docs/32.html", name: "休日や夜間の戸籍の届出について",
layout_id: layouts["faq"].id, category_ids: [categories["faq/kurashi"].id], question: "<p>休日や夜間でも戸籍の届出は可能でしょうか。</p>"
## -------------------------------------
puts "# ads"
banner1 = save_ss_files "ss_files/ads/dummy_banner_1.gif", filename: "dummy_banner_1.gif", model: "ads/banner"
banner2 = save_ss_files "ss_files/ads/dummy_banner_2.gif", filename: "dummy_banner_2.gif", model: "ads/banner"
banner3 = save_ss_files "ss_files/ads/dummy_banner_3.gif", filename: "dummy_banner_3.gif", model: "ads/banner"
banner4 = save_ss_files "ss_files/ads/dummy_banner_4.gif", filename: "dummy_banner_4.gif", model: "ads/banner"
banner5 = save_ss_files "ss_files/ads/dummy_banner_5.gif", filename: "dummy_banner_5.gif", model: "ads/banner"
banner6 = save_ss_files "ss_files/ads/dummy_banner_6.gif", filename: "dummy_banner_6.gif", model: "ads/banner"
banner1.set(state: "public")
banner2.set(state: "public")
banner3.set(state: "public")
banner4.set(state: "public")
banner5.set(state: "public")
banner6.set(state: "public")
save_page route: "ads/banner", filename: "add/600.html", name: "シラサギ", link_url: "http://www.ss-proj.org/", file_id: banner1.id
save_page route: "ads/banner", filename: "add/601.html", name: "シラサギ", link_url: "http://www.ss-proj.org/", file_id: banner2.id
save_page route: "ads/banner", filename: "add/602.html", name: "シラサギ", link_url: "http://www.ss-proj.org/", file_id: banner3.id
save_page route: "ads/banner", filename: "add/603.html", name: "シラサギ", link_url: "http://www.ss-proj.org/", file_id: banner4.id
save_page route: "ads/banner", filename: "add/604.html", name: "シラサギ", link_url: "http://www.ss-proj.org/", file_id: banner5.id
save_page route: "ads/banner", filename: "add/605.html", name: "シラサギ", link_url: "http://www.ss-proj.org/", file_id: banner6.id
## -------------------------------------
puts "# facility"
Dir.glob "ss_files/facility/*.*" do |file|
save_ss_files file, filename: File.basename(file), model: "facility/file"
end
array = SS::File.where(model: "facility/file").map { |m| [m.filename, m] }
facility_images = Hash[*array.flatten]
save_page route: "facility/image", filename: "institution/shisetsu/library/library.html", name: "シラサギ市立図書館",
layout_id: layouts["map"].id, image_id: facility_images["library.jpg"].id, order: 0
save_page route: "facility/image", filename: "institution/shisetsu/library/equipment.html", name: "設備",
layout_id: layouts["map"].id, image_id: facility_images["equipment.jpg"].id, order: 10
save_page route: "facility/map", filename: "institution/shisetsu/library/map.html", name: "地図",
layout_id: layouts["map"].id, map_points: [ { name: "シラサギ市立図書館", loc: [ 34.067035, 134.589971 ], text: "" } ]
puts "# ezine"
save_page route: "ezine/page", filename: "ezine/653.html", name: "シラサギ市メールマガジン", completed: true,
layout_id: layouts["ezine"].id, html: "<p>シラサギ市メールマガジンを配信します。</p>\r\n",
text: "シラサギ市メールマガジンを配信します。\r\n"
## -------------------------------------
def save_editor_template(data)
puts data[:name]
cond = { site_id: data[:site_id], name: data[:name] }
item = Cms::EditorTemplate.find_or_create_by(cond)
item.attributes = data
item.update
item
end
puts "# key visual"
keyvisual1 = save_ss_files "ss_files/key_visual/keyvisual01.jpg", filename: "keyvisual01.jpg", model: "key_visual/image"
keyvisual2 = save_ss_files "ss_files/key_visual/keyvisual02.jpg", filename: "keyvisual02.jpg", model: "key_visual/image"
keyvisual3 = save_ss_files "ss_files/key_visual/keyvisual03.jpg", filename: "keyvisual03.jpg", model: "key_visual/image"
keyvisual4 = save_ss_files "ss_files/key_visual/keyvisual04.jpg", filename: "keyvisual04.jpg", model: "key_visual/image"
keyvisual5 = save_ss_files "ss_files/key_visual/keyvisual05.jpg", filename: "keyvisual05.jpg", model: "key_visual/image"
keyvisual1.set(state: "public")
keyvisual2.set(state: "public")
keyvisual3.set(state: "public")
keyvisual4.set(state: "public")
keyvisual5.set(state: "public")
save_page route: "key_visual/image", filename: "key_visual/1.html", name: "キービジュアル1", order: 10, file_id: keyvisual1.id
save_page route: "key_visual/image", filename: "key_visual/2.html", name: "キービジュアル2", order: 20, file_id: keyvisual2.id
save_page route: "key_visual/image", filename: "key_visual/3.html", name: "キービジュアル3", order: 30, file_id: keyvisual3.id
save_page route: "key_visual/image", filename: "key_visual/4.html", name: "キービジュアル4", order: 40, file_id: keyvisual4.id
save_page route: "key_visual/image", filename: "key_visual/5.html", name: "キービジュアル5", order: 50, file_id: keyvisual5.id
puts "# editor templates"
thumb_left = save_ss_files("editor_templates/float-left.jpg", filename: "float-left.jpg", model: "cms/editor_template")
thumb_right = save_ss_files("editor_templates/float-right.jpg", filename: "float-right.jpg", model: "cms/editor_template")
editor_template_html = File.read("editor_templates/float-left.html") rescue nil
save_editor_template name: "画像左回り込み", description: "画像が左に回り込み右側がテキストになります",
html: editor_template_html, thumb_id: thumb_left.id, order: 10, site_id: @site.id
thumb_left.set(state: "public")
editor_template_html = File.read("editor_templates/float-right.html") rescue nil
save_editor_template name: "画像右回り込み", description: "画像が右に回り込み左側がテキストになります",
html: editor_template_html, thumb_id: thumb_right.id, order: 20, site_id: @site.id
thumb_right.set(state: "public")
editor_template_html = File.read("editor_templates/clear.html") rescue nil
save_editor_template name: "回り込み解除", description: "回り込みを解除します",
html: editor_template_html, order: 30, site_id: @site.id
puts "# cms pages"
save_page route: "cms/page", filename: "index.html", name: "自治体サンプル", layout_id: layouts["top"].id
save_page route: "cms/page", filename: "mobile.html", name: "スマートフォン・携帯サイト", layout_id: layouts["pages"].id
save_page route: "cms/page", filename: "use/index.html", name: "ご利用案内", layout_id: layouts["one"].id
save_page route: "cms/page", filename: "404.html", name: "お探しのページは見つかりません。 404 Not Found", layout_id: layouts["one"].id
save_page route: "cms/page", filename: "shisei/soshiki/index.html", name: "組織案内", layout_id: layouts["category-middle"].id
|
shirasagi/opendata
|
app/models/opendata/idea.rb
|
class Opendata::Idea
include Cms::Model::Page
include ::Workflow::Addon::Approver
include Opendata::Addon::Comment
include Opendata::Addon::Category
include Opendata::Addon::Area
include Opendata::Reference::Member
include Opendata::Common
include Cms::Addon::Release
include Contact::Addon::Page
include Cms::Addon::RelatedPage
include Cms::Addon::GroupPermission
include Workflow::MemberPermission
set_permission_name "opendata_ideas"
field :state, type: String, default: "public", overwrite: true
field :name, type: String, overwrite: true
field :point, type: Integer, default: "0"
field :text, type: String
field :tags, type: SS::Extensions::Words
field :commented, type: DateTime
field :total_comment, type: Integer, default: "0"
field :issue, type: String
field :data, type: String
field :note, type: String
embeds_ids :datasets, class_name: "Opendata::Dataset"
embeds_ids :apps, class_name: "Opendata::App"
belongs_to :member, class_name: "Opendata::Member"
has_many :points, foreign_key: :idea_id, class_name: "Opendata::IdeaPoint",
dependent: :delete
has_many :comments, foreign_key: :idea_id, class_name: "Opendata::IdeaComment",
dependent: :delete
validates :text, presence: true, length: { maximum: 400 }
validates :category_ids, presence: true
validates :state, presence: true
permit_params :text, :point, :commented, :total_comment, :tags, :dataset_ids, :app_ids, tags: [], dataset_ids: [], app_ids: []
permit_params :issue, :data, :note
before_save :seq_filename, if: ->{ basename.blank? }
default_scope ->{ where(route: "opendata/idea") }
scope :sort_criteria, ->(sort) do
case sort
when "attention"
excludes(commented: nil).order_by(sort_hash(sort))
else
order_by(sort_hash(sort))
end
end
public
def point_url
get_url(url, "/point.html")
end
def point_members_url
get_url(url, "/point/members.html")
end
def comment_url
get_url(url, "/comment/show.html")
end
def comment_add_url
get_url(url, "/comment/add.html")
end
def comment_delete_url
get_url(url, "/comment/delete.html")
end
def related_dataset_url
get_url(url, "/dataset/show.html")
end
def related_app_url
get_url(url, "/app/show.html")
end
def contact_present?
return false if member_id.present?
super
end
private
def validate_filename
@basename.blank? ? nil : super
end
def seq_filename
self.filename = dirname ? "#{dirname}#{id}.html" : "#{id}.html"
end
class << self
public
def to_idea_path(path)
suffix = %w(/point.html /point/members.html /comment/show.html /comment/add.html /comment/delete.html
/dataset/show.html /app/show.html).find { |suffix| path.end_with? suffix }
return path if suffix.blank?
path[0..(path.length - suffix.length - 1)] + '.html'
end
def sort_options
[
[I18n.t("opendata.sort_options.released"), "released"],
[I18n.t("opendata.sort_options.popular"), "popular"],
[I18n.t("opendata.sort_options.attention"), "attention"]
]
end
def sort_hash(sort)
case sort
when "released"
{ released: -1, _id: -1 }
when "popular"
{ point: -1, _id: -1 }
when "attention"
{ commented: -1, _id: -1 }
else
return { released: -1 } if sort.blank?
{ sort.sub(/ .*/, "") => (sort =~ /-1$/ ? -1 : 1) }
end
end
def aggregate_array(name, opts = {})
Opendata::Common.get_aggregate_array(self, name, opts)
end
def search_params
params = []
params << :keyword
params << :tag
params << :area_id
params << :category_id
params << :option
params
end
def search_options
%w(all_keywords any_keywords any_conditions).map do |w|
[I18n.t("opendata.search_options.#{w}"), w]
end
end
def search(params)
criteria = self.where({})
return criteria if params.blank?
SEARCH_HANDLERS.each do |handler|
criteria = send(handler, params, criteria)
end
criteria
end
private
SEARCH_HANDLERS = [ :search_keyword, :search_tag, :search_area_id, :search_category_id, :search_poster ].freeze
def search_keyword(params, criteria)
if params[:keyword].present?
option = params[:option].presence || 'all_keywords'
method = option == 'all_keywords' ? 'and' : 'any'
criteria = criteria.keyword_in params[:keyword], :name, :text, :issue, :data, :note, method: method
end
criteria
end
def search_tag(params, criteria)
if params[:tag].present?
operator = params[:option].presence == 'any_conditions' ? "$or" : "$and"
criteria = criteria.where(operator => [ tags: params[:tag] ])
end
criteria
end
def search_area_id(params, criteria)
if params[:area_id].present?
operator = params[:option].presence == 'any_conditions' ? "$or" : "$and"
criteria = criteria.where(operator => [ area_ids: params[:area_id].to_i ])
end
criteria
end
def search_category_id(params, criteria)
return criteria if params[:category_id].blank?
operator = params[:option].presence == 'any_conditions' ? "$or" : "$and"
category_id = params[:category_id].to_i
category_node = Cms::Node.site(params[:site]).public.where(id: category_id).first
return criteria if category_node.blank?
category_ids = [ category_id ]
category_node.all_children.public.each do |child|
category_ids << child.id
end
criteria.where(operator => [ category_ids: { "$in" => category_ids } ])
end
def search_poster(params, criteria)
if params[:poster].present?
cond = {}
cond = { :workflow_member_id.exists => true } if params[:poster] == "member"
cond = { :workflow_member_id => nil } if params[:poster] == "admin"
operator = params[:option].presence == 'any_conditions' ? "$or" : "$and"
criteria = criteria.where(operator => [ cond ])
end
criteria
end
end
end
|
shirasagi/opendata
|
lib/ss/rake_runner.rb
|
<reponame>shirasagi/opendata
class SS::RakeRunner
NULL_DEVICE = "/dev/null"
class << self
private
def do_spawn(task, *args)
Rails.logger.debug "spawn: bundle exec rake #{task} #{args.join(" ")}"
spawn({}, "bundle", "exec", "rake", task, *args, { in: NULL_DEVICE, out: NULL_DEVICE, err: NULL_DEVICE })
end
public
def run_async(task, *args)
pid = do_spawn(task, *args)
Process.detach(pid)
end
def run(task, *args)
pid = do_spawn(task, *args)
_, status = Process.waitpid2(pid)
status
end
end
end
|
shirasagi/opendata
|
spec/support/ss/file.rb
|
<reponame>shirasagi/opendata
class SS::File
def self.root
"#{Rails.root}/tmp/ss_files"
end
end
|
shirasagi/opendata
|
spec/features/cms/users_spec.rb
|
require 'spec_helper'
describe "cms_users", dbscope: :example do
subject(:site) { cms_site }
subject(:group) { cms_group }
subject(:item) { create(:cms_test_user, group: group) }
subject(:index_path) { cms_users_path site.host }
subject(:new_path) { new_cms_user_path site.host }
subject(:show_path) { cms_user_path site.host, item }
subject(:edit_path) { edit_cms_user_path site.host, item }
subject(:delete_path) { delete_cms_user_path site.host, item }
subject(:import_path) { import_cms_users_path site.host }
it "without login" do
visit index_path
expect(current_path).to eq sns_login_path
end
it "without auth" do
login_ss_user
visit index_path
expect(status_code).to eq 403
end
it "#index" do
login_cms_user
visit index_path
expect(current_path).not_to eq sns_login_path
end
context "with sns user" do
it "#new" do
login_cms_user
visit new_path
within "form#item-form" do
name = unique_id
fill_in "item[name]", with: name
fill_in "item[email]", with: <EMAIL>"
fill_in "item[in_password]", with: "<PASSWORD>"
check "item[group_ids][]"
check "item[cms_role_ids][]"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).not_to eq new_path
expect(page).not_to have_css("form#item-form")
end
it "#show" do
login_cms_user
visit show_path
expect(status_code).to eq 200
expect(current_path).not_to eq sns_login_path
end
it "#edit" do
login_cms_user
visit edit_path
within "form#item-form" do
fill_in "item[name]", with: "modify"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).not_to eq sns_login_path
expect(page).not_to have_css("form#item-form")
end
it "#delete" do
login_cms_user
visit delete_path
within "form" do
click_button "削除"
end
expect(status_code).to eq 200
expect(current_path).to eq index_path
end
end
context "with ldap user" do
it "#new" do
login_cms_user
visit new_path
within "form#item-form" do
name = unique_id
fill_in "item[name]", with: name
fill_in "item[uid]", with: name
fill_in "item[ldap_dn]", with: "dc=#{name},dc=city,dc=example,dc=jp"
check "item[group_ids][]"
check "item[cms_role_ids][]"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).not_to eq new_path
expect(page).not_to have_css("form#item-form")
end
it "#show" do
login_cms_user
visit show_path
expect(status_code).to eq 200
expect(current_path).not_to eq sns_login_path
end
it "#edit" do
login_cms_user
visit edit_path
within "form#item-form" do
fill_in "item[name]", with: "modify"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).not_to eq sns_login_path
expect(page).not_to have_css("form#item-form")
end
it "#delete" do
login_cms_user
visit delete_path
within "form" do
click_button "削除"
end
expect(status_code).to eq 200
expect(current_path).to eq index_path
end
end
context "import from csv" do
before(:each) do
g1 = create(:cms_group, name: "A", order: 10)
g2 = create(:cms_group, name: "A/B", order: 20)
g3 = create(:cms_group, name: "A/B/C", order: 30)
g4 = create(:cms_group, name: "A/B/D", order: 40)
r1 = create(:cms_role, name: "all")
r1 = create(:cms_role, name: "edit")
cms_site.add_to_set(group_ids: [g1.id, g2.id, g3.id, g4.id])
end
it "#import" do
login_cms_user
visit import_path
within "form" do
attach_file "item[in_file]", "#{Rails.root}/spec/fixtures/cms/user/cms_users_1.csv"
click_button "インポート"
end
expect(status_code).to eq 200
expect(current_path).to eq index_path
users = Cms::User.site(cms_site).ne(id: cms_user.id)
expected_emails = %w(
<EMAIL>
<EMAIL>
<EMAIL>
<EMAIL>
)
expected_names = %w(import_admin import_user1 import_user2 import_sys)
expected_uids = %w(admin user1 user2 sys)
expected_groups = [ ["A/B/C"], ["A/B/C", "A/B/D"], ["A/B/D"], ["A"] ]
expected_cms_roles = [ ["all"], ["edit"], ["edit"], ["all", "edit"] ]
expect(users.map(&:name)).to eq expected_names
expect(users.map(&:email)).to eq expected_emails
expect(users.map(&:uid)).to eq expected_uids
expect(users.map{|u| u.groups.map(&:name)}).to eq expected_groups
expect(users.map{|u| u.cms_roles.order_by(name: 1).map(&:name)}).to eq expected_cms_roles
end
end
end
|
shirasagi/opendata
|
app/controllers/member/agents/nodes/login_controller.rb
|
class Member::Agents::Nodes::LoginController < ApplicationController
include Cms::NodeFilter::View
include Member::LoginFilter
skip_filter :logged_in?, only: [:login, :logout, :callback, :failure]
private
def get_params
params.require(:item).permit(:email, :password)
end
def set_member_and_redirect(member)
set_member member
Member::ActivityLog.create(
cur_site: @cur_site,
cur_member: member,
activity_type: :login,
remote_addr: remote_addr,
user_agent: request.user_agent)
ref = URI::decode(params[:ref] || flash[:ref] || "")
ref = redirect_url if ref.blank?
flash.discard(:ref)
redirect_to ref
end
public
def login
@item = Cms::Member.new
unless request.post?
@error = flash[:alert]
flash[:ref] = params[:ref]
return
end
@item.attributes = get_params
member = Cms::Member.site(@cur_site).where(email: @item.email, password: <PASSWORD>(@item.password)).first
unless member
@error = t "sns.errors.invalid_login"
return
end
set_member_and_redirect member
end
def logout
# discard all session info
reset_session
redirect_to "#{member_login_path}"
end
def callback
auth = request.env["omniauth.auth"]
member = Cms::Member.where(oauth_type: auth.provider, oauth_id: auth.uid).first
if member.blank?
#外部認証していない場合、ログイン情報を保存してから、ログインさせる
Cms::Member.create_auth_member(auth, @cur_site)
member = Cms::Member.where(oauth_type: auth.provider, oauth_id: auth.uid).first
end
set_member_and_redirect member
end
def failure
session[:auth_site] = nil
session[:member] = nil
flash.discard(:ref)
redirect_to "#{@cur_node.url}/login.html"
end
end
|
shirasagi/opendata
|
spec/features/chorg/changesets_spec.rb
|
require 'spec_helper'
describe "chorg_changesets", dbscope: :example do
let(:site) { cms_site }
let(:revision) { create(:revision, site_id: site.id) }
let(:index_path) { chorg_changesets_changesets_path site.host, revision.id, "add" }
let(:revision_show_path) { chorg_revisions_revision_path site.host, revision.id }
it "without login" do
visit index_path
expect(current_path).to eq sns_login_path
end
it "without auth" do
login_ss_user
visit index_path
expect(status_code).to eq 403
end
it "#index" do
login_cms_user
visit index_path
expect(status_code).to eq 200
# redirected to "chorg/revisions#show"
expect(current_path).to eq revision_show_path
end
describe "#show" do
context "with add" do
let(:changeset) { create(:add_changeset, revision_id: revision.id) }
let(:add_show_path) { chorg_changesets_changeset_path site.host, revision.id, "add", changeset.id }
it do
# ensure that entities has existed.
expect(changeset).not_to be_nil
login_cms_user
visit add_show_path
expect(status_code).to eq 200
expect(page).to have_selector("div.addon-view dl.see")
end
it do
# ensure that entities has existed.
expect(changeset).not_to be_nil
# login
login_cms_user
%w(add move unify division delete).each do |type|
path = chorg_changesets_changeset_path(site.host, revision.id, type, changeset.id)
next if add_show_path == path
visit path
expect(status_code).to eq 404
end
end
end
context "with move" do
let(:group) { create(:revision_new_group) }
let(:changeset) { create(:move_changeset, revision_id: revision.id, source: group) }
let(:move_show_path) { chorg_changesets_changeset_path site.host, revision.id, "move", changeset.id }
it do
# ensure that entities has existed.
expect(changeset).not_to be_nil
login_cms_user
visit move_show_path
expect(status_code).to eq 200
expect(page).to have_selector("div.addon-view dl.see")
end
it do
# ensure that entities has existed.
expect(changeset).not_to be_nil
# login
login_cms_user
%w(add move unify division delete).each do |type|
path = chorg_changesets_changeset_path(site.host, revision.id, type, changeset.id)
next if move_show_path == path
visit path
expect(status_code).to eq 404
end
end
end
context "with unify" do
let(:group1) { create(:revision_new_group) }
let(:group2) { create(:revision_new_group) }
let(:changeset) { create(:unify_changeset, revision_id: revision.id, sources: [group1, group2]) }
let(:unify_show_path) { chorg_changesets_changeset_path site.host, revision.id, "unify", changeset.id }
it do
# ensure that entities has existed.
expect(changeset).not_to be_nil
login_cms_user
visit unify_show_path
expect(status_code).to eq 200
expect(page).to have_selector("div.addon-view dl.see")
end
it do
# ensure that entities has existed.
expect(changeset).not_to be_nil
# login
login_cms_user
%w(add move unify division delete).each do |type|
path = chorg_changesets_changeset_path(site.host, revision.id, type, changeset.id)
next if unify_show_path == path
visit path
expect(status_code).to eq 404
end
end
end
context "with division" do
let(:group0) { create(:revision_new_group) }
let(:group1) { build(:revision_new_group) }
let(:group2) { build(:revision_new_group) }
let(:changeset) do
create(:division_changeset, revision_id: revision.id, source: group0, destinations: [group1, group2])
end
let(:division_show_path) { chorg_changesets_changeset_path site.host, revision.id, "division", changeset.id }
it do
# ensure that entities has existed.
expect(changeset).not_to be_nil
login_cms_user
visit division_show_path
expect(status_code).to eq 200
expect(page).to have_selector("div.addon-view dl.see")
end
it do
# ensure that entities has existed.
expect(changeset).not_to be_nil
# login
login_cms_user
%w(add move unify division delete).each do |type|
path = chorg_changesets_changeset_path(site.host, revision.id, type, changeset.id)
next if division_show_path == path
visit path
expect(status_code).to eq 404
end
end
end
context "with delete" do
let(:group) { create(:revision_new_group) }
let(:changeset) { create(:delete_changeset, revision_id: revision.id, source: group) }
let(:delete_show_path) { chorg_changesets_changeset_path site.host, revision.id, "delete", changeset.id }
it do
# ensure that entities has existed.
expect(changeset).not_to be_nil
login_cms_user
visit delete_show_path
expect(status_code).to eq 200
expect(page).to have_selector("div.addon-view dl.see")
end
it do
# ensure that entities has existed.
expect(changeset).not_to be_nil
# login
login_cms_user
%w(add move unify division delete).each do |type|
path = chorg_changesets_changeset_path(site.host, revision.id, type, changeset.id)
next if delete_show_path == path
visit path
expect(status_code).to eq 404
end
end
end
end
end
|
shirasagi/opendata
|
app/controllers/facility/pages_controller.rb
|
<reponame>shirasagi/opendata<gh_stars>1-10
class Facility::PagesController < ApplicationController
include Cms::BaseFilter
include Cms::NodeFilter
include Facility::PageFilter
model Facility::Node::Page
prepend_view_path "app/views/cms/node/nodes"
menu_view "facility/page/menu"
private
def fix_params
{ cur_user: @cur_user, cur_site: @cur_site, cur_node: @cur_node }
end
def pre_params
{ route: "facility/page" }
end
def map_pages
Facility::Map.site(@cur_site).public.
where(filename: /^#{@item.filename}\//, depth: @item.depth + 1).order_by(order: 1)
end
def image_pages
Facility::Image.site(@cur_site).public.
where(filename: /^#{@item.filename}\//, depth: @item.depth + 1).order_by(order: 1).
select { |page| page.image.present? }
end
public
def show
raise "403" unless @item.allowed?(:read, @cur_user)
action = @cur_node.allowed?(:edit, @cur_user, site: @cur_site) ? "edit_" : ""
@maps = map_pages
@maps.each do |map|
points = []
map.map_points.each_with_index do |point, i|
points.push point
image_ids = @item.categories.pluck(:image_id)
points[i][:image] = SS::File.in(id: image_ids).first.try(:url)
end
map.map_points = points
if @merged_map
@merged_map.map_points += map.map_points
else
@merged_map = map
end
end
pages = image_pages.map do |page|
[
page,
send("#{action}facility_image_path", cid: @item.id, id: page.id ),
{ width: page.image_thumb_width, height: page.image_thumb_height }
]
end
@summary_image = [ pages.shift ].compact
@images = pages
end
end
|
shirasagi/opendata
|
app/models/concerns/cms/addon/sns_share.rb
|
module Cms::Addon
module SnsShare
extend ActiveSupport::Concern
extend SS::Addon
SERVICES = %w(fb_like fb_share twitter hatena google evernote)
included do
field :sns_share_states, type: Hash
field :sns_share_orders, type: Hash
permit_params sns_share_states: SERVICES, sns_share_orders: SERVICES
end
module ClassMethods
public
end
public
def sns_share_services
SERVICES
end
def sns_share_states_options
[
[I18n.t('views.options.state.show'), 'show'],
[I18n.t('views.options.state.hide'), 'hide'],
]
end
def sns_share_state(name)
sns_share_states.try(:[], name)
end
def sns_share_order(name)
sns_share_orders.try(:[], name)
end
def sns_share_state_label(name)
value = sns_share_state(name) != 'hide' ? 'show' : 'hide'
I18n.t("views.options.state.#{value}")
end
def sort_sns_share_services
list = sns_share_services
list = sns_share_orders.sort_by { |name, order| order } if sns_share_orders.present?
list = list.select do |name, _|
sns_share_state(name) != "hide"
end
list.map { |name, order| name }
end
end
end
|
shirasagi/opendata
|
spec/features/cms/node/parts_spec.rb
|
<gh_stars>1-10
require 'spec_helper'
describe "cms_node_parts" do
subject(:site) { cms_site }
subject(:node) { create_once :cms_node_page, name: "cms" }
subject(:item) { Cms::Part.last }
subject(:index_path) { node_parts_path site.host, node }
subject(:new_path) { new_node_part_path site.host, node }
subject(:show_path) { node_part_path site.host, node, item }
subject(:edit_path) { edit_node_part_path site.host, node, item }
subject(:delete_path) { delete_node_part_path site.host, node, item }
before(:all) do
# TODO:
# 前提条件:
# * Cms::Node::PartsController は Cms::PartFilter を include している。
# * Cms::PartFilter は Cms::NodeFilter を include している。
# * Cms::NodeFilter#set_item で、"@item.id == @cur_node.id" の場合 404 を発生させている。
# * つまり、パーツの ID と パーツを入れているフォルダの ID が同じ場合、404 となる。
#
# 問題点:
# 本テストを単独で実行した場合、node の ID は 1 である。
# 本テストの #new で初めてパーツが作成されるので、その ID は 1 である。
# このため @item.id = 1, @cur_node.id = 1 となり、条件 "@item.id == @cur_node.id" が成立し 404 が発生する。
# これを防ぐためにダミーのパーツを作成し、@item.id = 2 となるようにする。
Cms::Part.create!(site_id: cms_site.id, name: "dummy", basename: "dummy")
end
it "without login" do
visit index_path
expect(current_path).to eq sns_login_path
end
it "without auth" do
login_ss_user
visit index_path
expect(status_code).to eq 403
end
context "with auth" do
before { login_cms_user }
it "#index" do
visit index_path
expect(current_path).not_to eq sns_login_path
end
it "#new" do
visit new_path
within "form#item-form" do
fill_in "item[name]", with: "sample"
fill_in "item[basename]", with: "sample"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).not_to eq new_path
expect(page).not_to have_css("form#item-form")
end
it "#show" do
visit show_path
expect(status_code).to eq 200
expect(current_path).not_to eq sns_login_path
end
it "#edit" do
visit edit_path
within "form#item-form" do
fill_in "item[name]", with: "modify"
click_button "保存"
end
expect(current_path).not_to eq sns_login_path
expect(page).not_to have_css("form#item-form")
end
it "#delete" do
visit delete_path
within "form" do
click_button "削除"
end
expect(current_path).to eq index_path
end
end
end
|
shirasagi/opendata
|
spec/models/ss/file_spec.rb
|
require 'spec_helper'
describe SS::File do
describe "shirasagi-434" do
before do
@tmpdir = ::Dir.mktmpdir
@file_path = "#{@tmpdir}/#{filename}"
File.open(@file_path, "wb") do |file|
file.write [1]
end
end
after do
::FileUtils.rm_rf(@tmpdir)
end
before do
# we need custom setting for jtd
@save_config = SS.config.env.mime_type_map
SS.config.replace_value_at(:env, :mime_type_map, mime_type_map)
end
after do
SS.config.replace_value_at(:env, :mime_type_map, @save_config)
end
subject do
file = SS::File.new model: "article/page"
Fs::UploadedFile.create_from_file(@file_path, basename: "spec", content_type: "application/octet-stream") do |f|
file.in_file = f
file.save!
file.in_file = nil
end
file.reload
file
end
context "when pdf file is uploaded with application/octet-stream" do
let(:filename) { "a.pdf" }
let(:mime_type_map) { {} }
its(:content_type) { is_expected.to eq "application/pdf" }
end
context "when js file is uploaded with application/octet-stream" do
let(:filename) { "a.js" }
let(:mime_type_map) { {} }
its(:content_type) { is_expected.to eq "application/javascript" }
end
context "when jtd file is uploaded with application/octet-stream" do
let(:filename) { "a.jtd" }
let(:mime_type_map) { { "jtd" => "application/x-js-taro" } }
its(:content_type) { is_expected.to eq "application/x-js-taro" }
end
context "when wmv file is uploaded with application/octet-stream" do
let(:filename) { "a.wmv" }
let(:mime_type_map) { { "wmv" => "video/x-ms-wmv" } }
its(:content_type) { is_expected.to eq "video/x-ms-wmv" }
end
end
describe "#validate_size" do
let(:test_file_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png") }
let(:test_file) { Fs::UploadedFile.create_from_file(test_file_path, basename: "spec") }
after do
test_file.close unless test_file.closed?
end
subject do
file = SS::File.new model: "article/page"
file.in_file = test_file
file
end
context "when max_filesize is limited" do
before do
@save_config = SS.config.env.max_filesize
SS.config.replace_value_at(:env, :max_filesize, 50)
end
after do
SS.config.replace_value_at(:env, :max_filesize, @save_config)
end
it do
expect(subject.save).to be_falsey
expect(subject.errors[:base]).not_to be_empty
expect(subject.errors[:base].first).to include("logo.png", "サイズが大きすぎます", "制限値: 50バイト")
end
end
context "when max_filesize_ext is limited" do
before do
@save_config = SS.config.env.max_filesize_ext
SS.config.replace_value_at(:env, :max_filesize_ext, { "png" => 23 })
end
after do
SS.config.replace_value_at(:env, :max_filesize, @save_config)
end
it do
expect(subject.save).to be_falsey
expect(subject.errors[:base]).not_to be_empty
expect(subject.errors[:base].first).to include("logo.png", "サイズが大きすぎます", "制限値: 23バイト")
end
end
end
end
|
shirasagi/opendata
|
spec/factories/member/nodes.rb
|
FactoryGirl.define do
factory :member_node_login, class: Member::Node::Login, traits: [:cms_node] do
cur_site { cms_site }
route "member/login"
filename { SS.config.oauth.prefix_path.sub(/^\//, '') || "auth" }
twitter_oauth "enabled"
twitter_client_id { "#{unique_id}" }
twitter_client_secret { "#{unique_id}" }
facebook_oauth "enabled"
facebook_client_id { "#{unique_id}" }
facebook_client_secret { "#{unique_id}" }
end
end
|
shirasagi/opendata
|
app/models/concerns/ss/model/group.rb
|
module SS::Model::Group
extend ActiveSupport::Concern
extend SS::Translation
include SS::Document
include Ldap::Addon::Group
attr_accessor :in_password
included do
store_in collection: "ss_groups"
index({ name: 1 }, { unique: true })
seqid :id
field :name, type: String
field :order, type: Integer
permit_params :name, :order
default_scope -> { order_by(order: 1, name: 1) }
validates :name, presence: true, uniqueness: true, length: { maximum: 80 }
validate :validate_name
after_save :rename_children, if: ->{ @db_changes }
end
module ClassMethods
public
def search(params)
criteria = self.where({})
return criteria if params.blank?
if params[:name].present?
criteria = criteria.search_text params[:name]
end
if params[:keyword].present?
criteria = criteria.keyword_in params[:keyword], :name
end
criteria
end
end
private
def validate_name
if name =~ /\/$/ || name =~ /^\// || name =~ /\/\//
errors.add :name, :invalid
end
end
public
def full_name
name.gsub("/", " ")
end
def trailing_name
name.split("/").pop
end
def rename_children
return unless @db_changes["name"]
return unless @db_changes["name"][0]
return unless @db_changes["name"][1]
src = @db_changes["name"][0]
dst = @db_changes["name"][1]
SS::Group.where(name: /^#{Regexp.escape(src)}\//).each do |item|
item.name = item.name.sub(/^#{Regexp.escape(src)}\//, "#{dst}\/")
item.save validate: false
end
end
def root
parts = name.try(:split, "/") || []
return self if parts.length <= 1
0.upto(parts.length - 1) do |c|
ret = self.class.where(name: parts[0..c].join("/")).first
return ret if ret.present?
end
nil
end
def root?
id == root.id
end
end
|
shirasagi/opendata
|
app/controllers/concerns/ss/file_filter.rb
|
<filename>app/controllers/concerns/ss/file_filter.rb
module SS::FileFilter
extend ActiveSupport::Concern
private
def append_view_paths
append_view_path "app/views/ss/crud/files"
super
end
def set_last_modified
response.headers["Last-Modified"] = CGI::rfc1123_date(@item.updated.in_time_zone)
end
public
def create
@item = @model.new get_params
raise "403" unless @item.allowed?(:edit, @cur_user, site: @cur_site)
if @item.in_files
render_create @item.save_files, location: { action: :index }
else
render_create @item.save
end
end
def view
set_item
set_last_modified
if Fs.mode == :file && Fs.file?(@item.path)
send_file @item.path, type: @item.content_type, filename: @item.filename,
disposition: :inline, x_sendfile: true
else
send_data @item.read, type: @item.content_type, filename: @item.filename,
disposition: :inline
end
end
def thumb
set_item
set_last_modified
if @item.try(:thumb)
return send_file @item.thumb.path, type: @item.content_type, filename: @item.filename, disposition: :inline
end
require 'rmagick'
image = Magick::Image.from_blob(@item.read).shift
image = image.resize_to_fit 120, 90 if image.columns > 120 || image.rows > 90
send_data image.to_blob, type: @item.content_type, filename: @item.filename, disposition: :inline
rescue
raise "500"
end
def download
set_item
set_last_modified
if Fs.mode == :file && Fs.file?(@item.path)
send_file @item.path, type: @item.content_type, filename: @item.filename,
disposition: :attachment, x_sendfile: true
else
send_data @item.read, type: @item.content_type, filename: @item.filename,
disposition: :attachment
end
end
end
|
shirasagi/opendata
|
config/routes/opendata/mypage/routes.rb
|
SS::Application.routes.draw do
Opendata::Initializer
concern :deletion do
get :delete, on: :member
end
content "opendata" do
resources :mypages, concerns: :deletion, module: "mypage"
end
node "opendata" do
get "mypage/(index.html)" => "public#index", cell: "nodes/mypage/mypage"
get "mypage/notice/show.:format" => "public#show_notice", cell: "nodes/mypage/mypage", format: false
get "mypage/notice/confirm.:format" => "public#confirm_notice", cell: "nodes/mypage/mypage", format: false
resource :profile, path: "my_profile", controller: "public", cell: "nodes/mypage/my_profile", concerns: :deletion
end
part "opendata" do
get "mypage_login" => "public#index", cell: "parts/mypage/mypage_login"
end
end
|
shirasagi/opendata
|
app/controllers/cms/import_controller.rb
|
<reponame>shirasagi/opendata
class Cms::ImportController < ApplicationController
include Cms::BaseFilter
include Cms::CrudFilter
model Cms::Node::ImportNode
navi_view "cms/main/navi"
menu_view nil
public
def import
@item = @model.new get_params
@item.cur_site = @cur_site
result = @item.save_with_import
flash.now[:notice] = t("views.notice.saved") if !result && @item.imported > 0
render_create result, location: redirect_url, render: { file: :index }
end
private
def redirect_url
cms_import_path(cid: @cur_node)
end
end
|
shirasagi/opendata
|
app/helpers/opendata/list_helper.rb
|
module Opendata::ListHelper
def render_page_list(&block)
cur_item = @cur_part || @cur_node
cur_item.cur_date = @cur_date
h = []
h << cur_item.upper_html.html_safe if cur_item.upper_html.present?
if block_given?
h << capture(&block)
else
@items.each do |item|
if cur_item.loop_html.present?
ih = cur_item.render_loop_html(item)
else
ih = []
ih << '<article class="item-#{class} #{new} #{current}">'
ih << ' <header>'
ih << ' <time datetime="#{date.iso}">#{date.long}</time>'
ih << ' <h2>'
ih << ' <a href="#{url}">#{name}</a>'
if item.parent.becomes_with_route.show_point?
ih << ' <span class="point">#{point}</span>'
end
ih << ' </h2>'
ih << ' </header>'
ih << '</article>'
ih = cur_item.render_loop_html(item, html: ih.join("\n"))
end
h << ih.gsub('#{current}', current_url?(item.url).to_s)
end
end
h << cur_item.lower_html.html_safe if cur_item.lower_html.present?
h.join("\n").html_safe
end
def render_dataset_list(&block)
cur_item = @cur_part || @cur_node
cur_item.cur_date = @cur_date
dataset_node = Opendata::Node::Dataset.site(@cur_site).public.first
show_point = dataset_node.show_point?
h = []
if cur_item.upper_html.present?
h << cur_item.upper_html.html_safe
else
h << '<table class="opendata-datasets index">'
h << '<thead>'
h << '<tr>'
h << " <th class=\"name\">#{I18n.t('opendata.labels.dataset_name')}</th>"
h << " <th class=\"updated\">#{I18n.t('opendata.labels.update_datetime')}</th>"
h << " <th class=\"state\">#{I18n.t('opendata.labels.state')}</th>"
if show_point
h << " <th class=\"point\">#{I18n.t('opendata.labels.point')}</th>"
end
h << " <th class=\"downloaded\">#{I18n.t('opendata.labels.downloaded')}</th>"
if app_enabled?
h << " <th class=\"app\">#{I18n.t('opendata.labels.app')}</th>"
end
if idea_enabled?
h << " <th class=\"idea\">#{I18n.t('opendata.labels.idea')}</th>"
end
h << '</tr>'
h << '</thead>'
h << '<tbody>'
end
if block_given?
h << capture(&block)
else
@items.each do |item|
if cur_item.loop_html.present?
ih = cur_item.render_loop_html(item)
else
ih = []
ih << '<tr>'
ih << ' <td><a href="#{dataset_url}">#{dataset_name}</a></td>'
ih << ' <td>#{dataset_updated.%Y年%1m月%1d日 %1H時%1M分}</td>'
ih << ' <td>#{dataset_state}</td>'
if show_point
ih << ' <td>#{dataset_point}</td>'
end
ih << ' <td>#{dataset_downloaded}</td>'
if app_enabled?
ih << ' <td>#{dataset_apps_count}</td>'
end
if idea_enabled?
ih << ' <td>#{dataset_ideas_count}</td>'
end
ih << '</tr>'
ih = cur_item.render_loop_html(item, html: ih.join("\n"))
end
h << ih.gsub('#{current}', current_url?(item.url).to_s)
end
end
if cur_item.lower_html.present?
h << cur_item.lower_html.html_safe
else
h << '</tbody>'
h << '</table>'
end
h.join("\n").html_safe
end
def render_app_list(&block)
cur_item = @cur_part || @cur_node
cur_item.cur_date = @cur_date
app_node = Opendata::Node::App.site(@cur_site).public.first
show_point = app_node.show_point?
h = []
if cur_item.upper_html.present?
h << cur_item.upper_html.html_safe
else
h << '<table class="opendata-datasets index">'
h << '<thead>'
h << '<tr>'
h << " <th class=\"name\">#{I18n.t('opendata.labels.app_name')}</th>"
h << " <th class=\"updated\">#{I18n.t('opendata.labels.update_datetime')}</th>"
h << " <th class=\"state\">#{I18n.t('opendata.labels.state')}</th>"
if show_point
h << " <th class=\"point\">#{I18n.t('opendata.labels.point')}</th>"
end
h << '</tr>'
h << '</thead>'
h << '<tbody>'
end
if block_given?
h << capture(&block)
else
@items.each do |item|
if cur_item.loop_html.present?
ih = cur_item.render_loop_html(item)
else
ih = []
ih << '<tr>'
ih << ' <td><a href="#{app_url}">#{app_name}</a></td>'
ih << ' <td>#{app_updated.%Y年%1m月%1d日 %1H時%1M分}</td>'
ih << ' <td>#{app_state}</td>'
if show_point
ih << ' <td>#{app_point}</td>'
end
ih << '</tr>'
ih = cur_item.render_loop_html(item, html: ih.join("\n"))
end
h << ih.gsub('#{current}', current_url?(item.url).to_s)
end
end
if cur_item.lower_html.present?
h << cur_item.lower_html.html_safe
else
h << '</tbody>'
h << '</table>'
end
h.join("\n").html_safe
end
def render_idea_list(&block)
cur_item = @cur_part || @cur_node
cur_item.cur_date = @cur_date
idea_node = Opendata::Node::Idea.site(@cur_site).public.first
show_point = idea_node.show_point?
h = []
if cur_item.upper_html.present?
h << cur_item.upper_html.html_safe
else
h << '<table class="opendata-datasets index">'
h << '<thead>'
h << '<tr>'
h << " <th class=\"name\">#{I18n.t('opendata.labels.app_name')}</th>"
h << " <th class=\"updated\">#{I18n.t('opendata.labels.update_datetime')}</th>"
h << " <th class=\"state\">#{I18n.t('opendata.labels.state')}</th>"
if show_point
h << " <th class=\"point\">#{I18n.t('opendata.labels.point')}</th>"
end
if dataset_enabled?
h << " <th class=\"dataset\">#{I18n.t('opendata.labels.dataset')}</th>"
end
if app_enabled?
h << " <th class=\"app\">#{I18n.t('opendata.labels.app')}</th>"
end
h << '</tr>'
h << '</thead>'
h << '<tbody>'
end
if block_given?
h << capture(&block)
else
@items.each do |item|
if cur_item.loop_html.present?
ih = cur_item.render_loop_html(item)
else
ih = []
ih << '<tr>'
ih << ' <td><a href="#{idea_url}">#{idea_name}</a></td>'
ih << ' <td>#{idea_updated.%Y年%1m月%1d日 %1H時%1M分}</td>'
ih << ' <td>#{idea_state}</td>'
if show_point
ih << ' <td>#{idea_point}</td>'
end
if dataset_enabled?
ih << ' <td>#{idea_datasets}</td>'
end
if app_enabled?
ih << ' <td>#{idea_apps}</td>'
end
ih << '</tr>'
ih = cur_item.render_loop_html(item, html: ih.join("\n"))
end
h << ih.gsub('#{current}', current_url?(item.url).to_s)
end
end
if cur_item.lower_html.present?
h << cur_item.lower_html.html_safe
else
h << '</tbody>'
h << '</table>'
end
h.join("\n").html_safe
end
end
|
shirasagi/opendata
|
spec/features/article/pages_spec.rb
|
require 'spec_helper'
describe "article_pages", dbscope: :example do
let(:site) { cms_site }
let(:node) { create_once :article_node_page, filename: "docs", name: "article" }
let(:item) { create(:article_page, node: node) }
let(:index_path) { article_pages_path site.host, node }
let(:new_path) { new_article_page_path site.host, node }
let(:show_path) { article_page_path site.host, node, item }
let(:edit_path) { edit_article_page_path site.host, node, item }
let(:delete_path) { delete_article_page_path site.host, node, item }
let(:move_path) { move_article_page_path site.host, node, item }
let(:copy_path) { copy_article_page_path site.host, node, item }
let(:lock_path) { lock_article_page_path site.host, node, item }
it "without login" do
visit index_path
expect(current_path).to eq sns_login_path
end
it "without auth" do
login_ss_user
visit index_path
expect(status_code).to eq 403
end
context "with auth" do
before { login_cms_user }
it "#index" do
visit index_path
expect(current_path).not_to eq sns_login_path
end
it "#new" do
visit new_path
within "form#item-form" do
fill_in "item[name]", with: "sample"
fill_in "item[basename]", with: "sample"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).not_to eq new_path
expect(page).not_to have_css("form#item-form")
end
it "#show" do
visit show_path
expect(status_code).to eq 200
expect(current_path).not_to eq sns_login_path
end
it "#edit" do
visit edit_path
within "form#item-form" do
fill_in "item[name]", with: "modify"
click_button "保存"
end
expect(current_path).not_to eq sns_login_path
expect(page).not_to have_css("form#item-form")
end
it "#move" do
visit move_path
within "form" do
fill_in "destination", with: "docs/destination"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).to eq move_path
expect(page).to have_css("form#item-form h2", text: "docs/destination.html")
within "form" do
fill_in "destination", with: "docs/sample"
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).to eq move_path
expect(page).to have_css("form#item-form h2", text: "docs/sample.html")
end
it "#copy" do
visit copy_path
within "form" do
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).to eq index_path
expect(page).to have_css("a", text: "[複製] #{item.name}")
expect(page).to have_css(".state", text: "非公開")
end
it "#delete" do
visit delete_path
within "form" do
click_button "削除"
end
expect(current_path).to eq index_path
end
feature "lock and unlock" do
given(:group) { cms_group }
given(:user1) { create(:cms_test_user, group: group) }
background do
item.acquire_lock(user: user1)
end
scenario "locked by other then unlock and edit forcibly" do
expect(item.lock_owner_id).not_to eq cms_user.id
visit show_path
expect(status_code).to eq 200
within "div#addon-cms-agents-addons-edit_lock" do
expect(page).to have_content(I18n.t("errors.messages.locked", user: item.lock_owner.long_name))
end
click_link "編集する"
expect(status_code).to eq 200
expect(current_path).to eq lock_path
click_button I18n.t("views.button.unlock_and_edit_forcibly")
expect(status_code).to eq 200
expect(current_path).to eq edit_path
item.reload
expect(item.lock_owner_id).to eq cms_user.id
end
end
end
end
|
shirasagi/opendata
|
app/models/oauth/base.rb
|
require 'oauth2'
module Oauth::Base
def site
host = @env["HTTP_X_FORWARDED_HOST"] || @env["HTTP_HOST"]
@site ||= SS::Site.find_by_domain host
end
def node
path = request.env["REQUEST_PATH"]
@node ||= Member::Node::Login.site(site).in_path(path).sort(depth: -1).first
end
def client_id
@client_id ||= begin
Rails.logger.debug("fetch client id from #{node.try(:filename)} node")
id = node.try("#{name}_client_id".downcase)
id = SS.config.oauth.try(:[], "#{name}_client_id") if id.blank?
id
end
end
def client_secret
@client_secret ||= begin
Rails.logger.debug("fetch client secret from #{node.try(:filename)} node")
secret = node.try("#{name}_client_secret".downcase)
secret = SS.config.oauth.try(:[], "#{name}_client_secret") if secret.blank?
secret
end
end
# override OmniAuth::Strategies::OAuth2#client
def client
::OAuth2::Client.new(client_id, client_secret, deep_symbolize(options.client_options))
end
end
|
shirasagi/opendata
|
spec/requests/article/pages_spec.rb
|
<reponame>shirasagi/opendata<gh_stars>1-10
require 'spec_helper'
describe "Article::PagesController", type: :request, dbscope: :example do
let!(:group) { cms_group }
let!(:site) { cms_site }
let!(:node) { create(:article_node_page) }
let(:auth_token_path) { sns_auth_token_path(format: :json) }
let(:index_path) { article_pages_path(site.host, node, format: :json) }
let!(:admin_user) { cms_user }
context "admin user" do
before do
# get and save auth token
get auth_token_path
@auth_token = JSON.parse(response.body)["auth_token"]
# login
params = {
'authenticity_token' => @auth_token,
'item[email]' => admin_user.email,
'item[password]' => <PASSWORD> }
post sns_login_path(format: :json), params
end
describe "GET /pages.json" do
let!(:page) { create(:article_page, node: node) }
it do
get index_path
expect(response.status).to eq 200
list = JSON.parse(response.body)
expect(list.length).to eq 1
expect(list[0]["_id"]).to eq 1
expect(list[0]["name"]).to eq page.name
expect(list[0]["filename"]).to eq page.filename
end
end
describe "POST /pages.json" do
it do
params = { 'authenticity_token' => @auth_token,
'item[name]' => '記事タイトル',
'item[basename]' => "filename#{rand(0xffffffff).to_s(36)}" }
post index_path, params
expect(response.status).to eq 201
page = JSON.parse(response.body)
expect(page["_id"]).to eq 1
expect(page["name"]).to eq params['item[name]']
expect(page["filename"]).to eq "#{node.filename}/#{params['item[basename]']}.html"
end
end
describe "GET /page/:id/lock.json" do
let!(:item) { create(:article_page, node: node) }
let!(:lock_path) { lock_article_page_path(site.host, node, item, format: :json) }
context "with no lock" do
it do
get lock_path
expect(response.status).to eq 200
item.reload
expect(item.lock_owner_id).to eq admin_user.id
end
end
context "with not owned lock" do
let(:group) { cms_group }
let(:user1) { create(:cms_test_user, group: group) }
before do
item.acquire_lock(user: user1)
end
it do
get lock_path
expect(response.status).to eq 423
item.reload
expect(item.lock_owner_id).to eq user1.id
end
end
end
describe "DELETE /page/:id/lock.json" do
let!(:item) { create(:article_page, node: node) }
let!(:lock_path) { lock_article_page_path(site.host, node, item, format: :json) }
context "with owned lock" do
before do
item.acquire_lock(user: admin_user)
end
it do
expect(item.lock_owner_id).to eq admin_user.id
delete lock_path
expect(response.status).to eq 204
item.reload
expect(item.lock_owner_id).to be_nil
end
end
context "with not owned lock" do
let(:group) { cms_group }
let(:user1) { create(:cms_test_user, group: group) }
before do
item.acquire_lock(user: user1)
end
it do
delete lock_path
expect(response.status).to eq 423
item.reload
expect(item.lock_owner_id).to eq user1.id
end
end
context "with owned lock and unlock twice" do
before do
item.acquire_lock(user: admin_user)
end
it do
expect(item.lock_owner_id).to eq admin_user.id
2.times do
delete lock_path
expect(response.status).to eq 204
end
item.reload
expect(item.lock_owner_id).to be_nil
end
end
end
end
context "user which does not have unlock privilege" do
let!(:role) do
Cms::Role.create!(
name: "role_#{unique_id}",
permissions: Cms::Role.permission_names.reject { |name| name.start_with?('unlock_') },
site_id: site.id
)
end
let!(:user) { create(:cms_test_user, group: group, role: role) }
before do
# get and save auth token
get auth_token_path
@auth_token = JSON.parse(response.body)["auth_token"]
# login
params = { 'authenticity_token' => @auth_token, 'item[email]' => user.email, 'item[password]' => <PASSWORD> }
post sns_login_path(format: :json), params
end
describe "GET /page/:id/lock.json" do
let!(:item) { create(:article_page, node: node) }
let!(:lock_path) { lock_article_page_path(site.host, node, item, format: :json) }
context "with no lock" do
it do
get lock_path
expect(response.status).to eq 200
item.reload
expect(item.lock_owner_id).to eq user.id
end
end
context "with not owned lock" do
let(:group) { cms_group }
let(:user1) { create(:cms_test_user, group: group) }
before do
item.acquire_lock(user: user1)
end
it do
get lock_path
expect(response.status).to eq 423
item.reload
expect(item.lock_owner_id).to eq user1.id
end
end
end
describe "DELETE /page/:id/lock.json" do
let!(:item) { create(:article_page, node: node) }
let!(:lock_path) { lock_article_page_path(site.host, node, item, format: :json) }
context "with owned lock" do
before do
item.acquire_lock(user: user)
end
it do
expect(item.lock_owner_id).to eq user.id
delete lock_path
expect(response.status).to eq 204
item.reload
expect(item.lock_owner_id).to be_nil
end
end
context "with not owned lock" do
let(:group) { cms_group }
let(:user1) { create(:cms_test_user, group: group) }
before do
item.acquire_lock(user: user1)
end
it do
delete lock_path
# expected to get 403 because user does not have unlock privilege
expect(response.status).to eq 403
item.reload
expect(item.lock_owner_id).to eq user1.id
end
end
context "with owned lock and unlock twice" do
before do
item.acquire_lock(user: user)
end
it do
expect(item.lock_owner_id).to eq user.id
2.times do
delete lock_path
expect(response.status).to eq 204
end
item.reload
expect(item.lock_owner_id).to be_nil
end
end
end
end
end
|
shirasagi/opendata
|
spec/features/cms/import_spec.rb
|
require 'spec_helper'
describe "cms_import" do
subject(:site) { cms_site }
subject(:index_path) { cms_import_path site.host }
it "without login" do
visit index_path
expect(current_path).to eq sns_login_path
end
it "without auth" do
login_ss_user
visit index_path
expect(status_code).to eq 403
end
context "with auth", js: true do
before { login_cms_user }
it "#index" do
visit index_path
expect(status_code).to eq 200
expect(current_path).to eq index_path
end
it "#import" do
visit index_path
within "form#item-form" do
attach_file "item[in_file]", "#{Rails.root}/spec/fixtures/cms/import/site.zip"
wait_for_ajax
click_button "取り込み"
end
expect(status_code).to eq 200
pages = Cms::ImportPage.all.entries
nodes = Cms::Node::ImportNode.all.entries
expect(pages.map(&:name)).to eq %w(1.html index.html)
expect(nodes.map(&:name)).to eq %w(site article css img)
end
end
end
|
shirasagi/opendata
|
app/models/concerns/inquiry/addon/captcha.rb
|
module Inquiry::Addon
module Captcha
extend ActiveSupport::Concern
extend SS::Addon
included do
field :inquiry_captcha, type: String, default: "enabled"
permit_params :inquiry_captcha
end
public
def inquiry_captcha_options
[
[I18n.t('inquiry.options.state.enabled'), 'enabled'],
[I18n.t('inquiry.options.state.disabled'), 'disabled'],
]
end
def captcha_enabled?
inquiry_captcha == "enabled"
end
end
end
|
shirasagi/opendata
|
app/controllers/concerns/opendata/api/tag_show_filter.rb
|
<reponame>shirasagi/opendata
module Opendata::Api::TagShowFilter
extend ActiveSupport::Concern
include Opendata::Api
public
def tag_show
help = t("opendata.api.tag_show_help")
id = params[:id]
id = URI.decode(id) if id
if !id
error = {__type: "Validation Error", id: "Missing value"}
render json: {help: help, success: false, error: error} and return
end
datasets = Opendata::Dataset.site(@cur_site).public.search({tag: id})
if datasets.count > 0
res = {help: help, success: true, result: convert_packages(datasets)}
else
res = {help: help, success: false}
res[:error] = {message: "Not found", __type: "Not Found Error"}
end
render json: res
end
end
|
shirasagi/opendata
|
app/controllers/opendata/agents/nodes/app/app_category_controller.rb
|
class Opendata::Agents::Nodes::App::AppCategoryController < ApplicationController
include Cms::NodeFilter::View
include Opendata::UrlHelper
include Opendata::App::AppFilter
private
def pages
@cur_node.cur_subcategory = params[:name]
@item = @cur_node.related_category
raise "404" unless @item
@cur_node.name = @item.name
Opendata::App.site(@cur_site).search(site: @cur_site, category_id: @item.id).public
end
def node_url
if name = params[:name]
"#{@cur_node.url}#{name}/"
else
"#{@cur_node.url}"
end
end
public
def index
@count = pages.size
@node_url = node_url
default_options = { "s[category_id]" => "#{@item.id}" }
@search_path = ->(options = {}) { search_apps_path(default_options.merge(options)) }
@rss_path = ->(options = {}) { build_path("#{search_apps_path}rss.xml", default_options.merge(options)) }
@items = pages.order_by(released: -1).limit(10)
@point_items = pages.order_by(point: -1).limit(10)
@execute_items = pages.order_by(executed: -1).limit(10)
@app_node = @cur_node.parent_app_node
controller.instance_variable_set :@cur_node, @item
@tabs = []
if @app_node.show_tab?("released")
@tabs << { name: @app_node.tab_title("released").presence || I18n.t("opendata.sort_options.released"),
id: "released",
url: "#{@search_path.call("sort" => "released")}",
pages: @items,
rss: "#{@rss_path.call("sort" => "released")}" }
end
if @app_node.show_tab?("popular")
@tabs << { name: @app_node.tab_title("popular").presence || I18n.t("opendata.sort_options.popular"),
id: "popular",
url: "#{@search_path.call("sort" => "popular")}",
pages: @point_items,
rss: "#{@rss_path.call("sort" => "popular")}" }
end
if @app_node.show_tab?("attention")
@tabs << { name: @app_node.tab_title("attention").presence || I18n.t("opendata.sort_options.attention"),
id: "attention",
url: "#{@search_path.call("sort" => "attention")}",
pages: @execute_items,
rss: "#{@rss_path.call("sort" => "attention")}" }
end
max = 50
@areas = aggregate_areas(max)
@tags = aggregate_tags(max)
@licenses = aggregate_licenses(max)
end
def rss
@items = pages.order_by(released: -1).limit(100)
render_rss @cur_node, @items
end
end
|
shirasagi/opendata
|
spec/helpers/opendata/list_helper_spec.rb
|
<filename>spec/helpers/opendata/list_helper_spec.rb
require 'spec_helper'
describe Opendata::ListHelper, type: :helper, dbscope: :example do
describe ".render_page_list" do
context "without block" do
subject { helper.render_page_list }
before do
@cur_site = cms_site
create(:opendata_node_search_dataset)
@cur_part = create(:opendata_part_dataset)
@cur_node = create(:opendata_node_dataset)
@cur_path = @cur_node.filename
@item1 = create(:opendata_dataset, node: @cur_node)
@item2 = create(:opendata_dataset, node: @cur_node)
@item3 = create(:opendata_dataset, node: @cur_node)
@items = Opendata::Dataset.all
end
it do
is_expected.to include "<article class=\"item-#{@item1.basename.sub(/\..*/, "").dasherize} new \">"
is_expected.to include "<article class=\"item-#{@item2.basename.sub(/\..*/, "").dasherize} new \">"
is_expected.to include "<article class=\"item-#{@item3.basename.sub(/\..*/, "").dasherize} new \">"
end
end
context "with block" do
let(:now) { Time.zone.now }
subject do
helper.render_page_list { "現在の時刻は#{now}" }
end
before do
@cur_site = cms_site
create(:opendata_node_search_dataset)
@cur_part = create(:opendata_part_dataset)
@cur_node = create(:opendata_node_dataset)
@cur_path = @cur_node.filename
@item1 = create(:opendata_dataset, node: @cur_node)
@item2 = create(:opendata_dataset, node: @cur_node)
@item3 = create(:opendata_dataset, node: @cur_node)
@items = Opendata::Dataset.all
end
it do
is_expected.to include "現在の時刻は#{now}"
end
end
end
end
|
shirasagi/opendata
|
app/models/concerns/cms/addon/node_setting.rb
|
<filename>app/models/concerns/cms/addon/node_setting.rb
module Cms::Addon
module NodeSetting
extend ActiveSupport::Concern
extend SS::Addon
included do
field :view_route, type: String
permit_params :view_route
end
end
end
|
shirasagi/opendata
|
spec/factories/opendata/dataset_groups.rb
|
FactoryGirl.define do
factory :opendata_dataset_group, class: Opendata::DatasetGroup do
transient do
site nil
user nil
categories nil
end
name { "#{unique_id}" }
site_id { site.present? ? site.id : cms_site.id }
user_id { user.present? ? user.id : nil }
category_ids { categories.present? ? categories.map(&:_id).to_a : nil }
end
end
|
shirasagi/opendata
|
app/models/concerns/ss/model/role.rb
|
<filename>app/models/concerns/ss/model/role.rb
module SS::Model::Role
extend ActiveSupport::Concern
extend SS::Translation
include SS::Document
include SS::Reference::User
included do
cattr_accessor(:_permission_names) { [] }
cattr_accessor(:_module_permission_names) { {} }
seqid :id
field :name, type: String
field :permissions, type: SS::Extensions::Words
permit_params :name, permissions: [] #TODO:
validates :name, presence: true, length: { maximum: 80 }
class << self
def permission(name, opts = {})
module_name = opts[:module_name] || name.to_s.sub(/^[a-z]+_(private_|other_|member_)?(.*)?_.*/, '\\2')
module_name = :"#{module_name}"
self._permission_names << name.to_s
self._module_permission_names[module_name] ||= []
self._module_permission_names[module_name] << name
end
def permission_names
_permission_names.sort
end
def module_permission_names
_module_permission_names.sort_by { |k, v| k }.map do |k, v|
[k, v.sort_by { |name| I18n.t("cms_role.#{name}") } ]
end
end
end
end
end
|
shirasagi/opendata
|
lib/ldap/group.rb
|
class Ldap::Group < Ldap::Entry
def initialize(connection, entry)
super(connection, entry)
end
end
class Ldap::OrganizationalUnit < Ldap::Group
public_class_method :new
def name
value(:ou)
end
def contact_tel
value(:telephoneNumber)
end
def self.support?(object_classes)
object_classes.include?("organizationalUnit")
end
def self.filter
Net::LDAP::Filter.construct("(objectClass=organizationalUnit)")
end
end
class Ldap::Organization < Ldap::Group
public_class_method :new
def name
value(:o)
end
def contact_tel
value(:telephoneNumber)
end
def self.support?(object_classes)
object_classes.include?("organization")
end
def self.filter
Net::LDAP::Filter.construct("(objectClass=organization)")
end
end
# class Ldap::PosixGroup < Ldap::Group
# public_class_method :new
#
# def name
# value(:cn)
# end
#
# def contact_tel
# nil
# end
#
# def self.support?(object_classes)
# object_classes.include?("posixGroup")
# end
#
# def self.filter
# Net::LDAP::Filter.construct("(objectClass=posixGroup)")
# end
#
# def users
# self[:memberuid].uniq.map do |memberuid|
# filter = Net::LDAP::Filter.construct("(&(objectClass=posixAccount)(uid=#{memberuid}))")
# @connection.search(filter, scope: Net::LDAP::SearchScope_WholeSubtree).map do |e|
# Ldap::User.create(@connection, e)
# end
# end.uniq.flatten
# end
# end
class Ldap::Group
private_class_method :new
# CONCRETE_CLASSES = [ Ldap::OrganizationalUnit, Ldap::Organization, Ldap::PosixGroup ].freeze
CONCRETE_CLASSES = [ Ldap::OrganizationalUnit, Ldap::Organization ].freeze
DEFAULT_FILTER = CONCRETE_CLASSES.map { |c| c.filter }.reduce { |a, e| a | e }
def self.create(connection, entry)
object_classes = Ldap::Entry.normalize(entry[:objectClass])
CONCRETE_CLASSES.each do |c|
return c.new(connection, entry) if c.support?(object_classes)
end
Rails.logger.info("unknown object class: #{object_classes}")
nil
end
def groups
@connection.search(DEFAULT_FILTER, base: dn).map do |e|
self.class.create(@connection, e)
end
end
def users
@connection.search(Ldap::User::DEFAULT_FILTER, base: dn).map do |e|
Ldap::User.create(@connection, e)
end
end
end
|
shirasagi/opendata
|
app/models/concerns/cms/addon/html.rb
|
module Cms::Addon
module Html
extend ActiveSupport::Concern
extend SS::Addon
included do
field :html, type: String, metadata: { form: :text }
permit_params :html
end
end
end
|
shirasagi/opendata
|
lib/tasks/cms/seeds/export.rake
|
<reponame>shirasagi/opendata<filename>lib/tasks/cms/seeds/export.rake
namespace :cms do
def find_layout(site, layout)
ret = Cms::Layout.site(site).where(_id: layout).first
ret ||= Cms::Layout.site(site).where(filename: layout).first
ret ||= Cms::Layout.site(site).where(name: layout).first
ret
end
def find_page(site, page)
ret = Cms::Page.site(site).where(_id: page).first
ret ||= Cms::Page.site(site).where(filename: page).first
ret ||= Cms::Page.site(site).where(name: page).first
ret = ret.becomes_with_route if ret.present?
ret
end
namespace :seeds do
task :export_layouts => :environment do
site = SS::Site.where(host: ENV['site']).first
next unless site
output_dir = ENV["output"] || 'layouts'
::FileUtils.mkdir_p(output_dir) unless ::Dir.exist?(output_dir)
Cms::Layout.site(site).each do |layout|
filename = "#{output_dir}/#{layout.filename}"
dirname = ::File.dirname(filename)
::FileUtils.mkdir_p(dirname) unless ::Dir.exist?(dirname)
open(filename, "w") do |f|
f.write layout.html.gsub("\r\n", "\n")
end
puts "save_layout filename: \"#{layout.filename}\", name: \"#{layout.name}\""
end
end
task :export_parts => :environment do
site = SS::Site.where(host: ENV['site']).first
next unless site
output_dir = ENV["output"] || 'parts'
::FileUtils.mkdir_p(output_dir) unless ::Dir.exist?(output_dir)
Cms::Part.site(site).each do |part|
part = part.becomes_with_route || part
filename = "#{output_dir}/#{part.filename}"
dirname = ::File.dirname(filename)
::FileUtils.mkdir_p(dirname) unless ::Dir.exist?(dirname)
html = part.html rescue nil
if html.present? && html.is_a?(String)
open(filename, "w") do |f|
f.write html.gsub("\r\n", "\n")
end
end
upper_html = part.upper_html rescue nil
if upper_html.present? && upper_html.is_a?(String)
open(filename.sub(/\.html$/, ".upper_html"), "w") do |f|
f.write upper_html.gsub("\r\n", "\n")
end
end
loop_html = part.loop_html rescue nil
if loop_html.present? && loop_html.is_a?(String)
open(filename.sub(/\.html$/, ".loop_html"), "w") do |f|
f.write loop_html.gsub("\r\n", "\n")
end
end
lower_html = part.lower_html rescue nil
if lower_html.present? && lower_html.is_a?(String)
open(filename.sub(/\.html$/, ".lower_html"), "w") do |f|
f.write lower_html.gsub("\r\n", "\n")
end
end
message = "save_part filename: \"#{part.filename}\", name: \"#{part.name}\", route: \"#{part.route}\""
message << ", ajax_view: \"enabled\"" if part.ajax_view.present? && part.ajax_view == 'enabled'
message << ", conditions: %w(#{part.conditions.join(' ')})" if part.try(:conditions).present?
message << ", limit: #{part.limit}" if part.try(:limit).present?
message << ", sort: \"#{part.sort}\"" if part.try(:sort).present?
puts message
end
end
task :export_page => :environment do
site = SS::Site.where(host: ENV['site']).first
next unless site
page = find_page(site, ENV['page'])
next unless page
output_dir = ENV["output"] || 'pages'
::FileUtils.mkdir_p(output_dir) unless ::Dir.exist?(output_dir)
filename = "#{output_dir}/#{page.filename}"
dirname = ::File.dirname(filename)
::FileUtils.mkdir_p(dirname) unless ::Dir.exist?(dirname)
html = page.try(:html)
if html.present?
open(filename, "w") do |f|
f.write html.gsub("\r\n", "\n")
end
end
summary_html = page.try(:summary_html)
if summary_html.present?
open(filename.sub(/\.html$/, "") + ".summary_html", "w") do |f|
f.write summary_html.gsub("\r\n", "\n")
end
end
message = "save_page route: \"#{page.route}\""
message << ", filename: \"#{page.filename}\""
message << ", name: \"#{page.name}\""
message << ", layout_id: layouts[\"#{page.layout.filename.sub(/\..*$/, '')}\"].id"
puts message
end
end
end
|
shirasagi/opendata
|
spec/support/ss/mongoid.rb
|
# mongoid
shared_examples "mongoid#save" do
it { expect { build(factory).save! }.not_to raise_error }
end
shared_examples "mongoid#find" do
it { expect(model.first).not_to eq nil }
#it { expect(model.all.size).not_to eq 0 }
end
module Mongoid
module Tasks
module Database
private
# rewrite logger method.
def self.logger
Rails.logger
end
end
end
end
|
shirasagi/opendata
|
spec/features/opendata/agents/nodes/mypage/dataset/my_dataset/resources_spec.rb
|
require 'spec_helper'
describe "opendata_agents_nodes_my_dataset_resources", dbscope: :example do
let(:site) { cms_site }
let(:member) { opendata_member(site: site) }
let!(:node_member) { create :opendata_node_member }
let!(:node_search_dataset) { create_once :opendata_node_search_dataset, basename: "dataset/search" }
let!(:node_dataset) { create :opendata_node_dataset }
let!(:node_mypage) { create :opendata_node_mypage, filename: "mypage" }
let!(:node_my_dataset) { create :opendata_node_my_dataset, filename: "#{node_mypage.filename}/dataset" }
let!(:node_login) { create :member_node_login, redirect_url: node_my_dataset.url }
let!(:category) { create :opendata_node_category, name: "カテゴリー01" }
let!(:node_area) { create :opendata_node_area, name: "地域A" }
let!(:node_search) { create :opendata_node_search_dataset }
let!(:dataset) { create :opendata_dataset, node: node_dataset, member_id: member.id }
let(:license_logo_file_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png") }
let(:license_logo_file) { Fs::UploadedFile.create_from_file(license_logo_file_path, basename: "spec") }
let!(:license) { create(:opendata_license, site: site, file: license_logo_file) }
let(:index_url) { ::URI.parse "http://#{site.domain}#{node_my_dataset.url}" }
let(:item_name) { "リソース01" }
let(:item_name2) { "リソース02" }
let(:item_text) { "リソース内容01" }
let(:item_text2) { "リソース内容02" }
before do
login_opendata_member(site, node_login, member)
end
after do
logout_opendata_member(site, node_login, member)
end
describe "create/edit/delete resource" do
it do
visit index_url
expect(current_path).to eq index_url.path
expect(status_code).to eq 200
click_link dataset.name
click_link 'リソースを管理する'
click_link '新規作成'
expect(status_code).to eq 200
within "form#item-form" do
fill_in "item_name", with: item_name
fill_in "item_format", with: "CSV"
fill_in "item_text", with: item_text
attach_file "item[in_file]", "#{Rails.root}/spec/fixtures/opendata/shift_jis.csv"
select license.name, from: "item_license_id"
click_button "公開保存"
end
expect(status_code).to eq 200
within "table.opendata-resources" do
expect(page).to have_content(item_name)
click_link item_name
end
expect(status_code).to eq 200
within "nav.menu" do
click_link '編集'
end
expect(status_code).to eq 200
within "form#item-form" do
fill_in "item_name", with: item_name2
fill_in "item_text", with: item_text2
click_button "公開保存"
end
expect(status_code).to eq 200
within "table.opendata-dataset-resources" do
expect(page).not_to have_content(item_name)
expect(page).to have_content(item_name2)
end
within "nav.menu" do
click_link '削除'
end
within "form#item-form" do
click_button '削除'
end
expect(status_code).to eq 200
within "table.opendata-resources" do
expect(page).not_to have_content(item_name)
expect(page).not_to have_content(item_name2)
end
end
end
end
|
shirasagi/opendata
|
spec/features/opendata/agents/nodes/member_spec.rb
|
<reponame>shirasagi/opendata
require 'spec_helper'
describe "opendata_agents_nodes_member", dbscope: :example do
let(:site) { cms_site }
let(:node_member) { create_once :opendata_node_member }
let(:index_path) { "#{node_member.url}index.html" }
describe "index" do
it do
page.driver.browser.with_session("public") do |session|
session.env("HTTP_X_FORWARDED_HOST", site.domain)
expect { visit index_path }.to raise_error RuntimeError
end
end
end
describe "show and dataset" do
let(:member) { opendata_member }
let(:show_path) { "#{node_member.url}#{member.id}/" }
it do
page.driver.browser.with_session("public") do |session|
session.env("HTTP_X_FORWARDED_HOST", site.domain)
visit show_path
expect(page).to have_selector("article#cms-tab-#{member.id}-0")
expect(page).to have_selector("article#cms-tab-#{member.id}-1")
expect(page).to have_selector("article#cms-tab-#{member.id}-2")
within "article#cms-tab-#{member.id}-0" do
click_link "もっと見る"
end
expect(page).to have_selector("section.datasets")
end
end
end
describe "show and app" do
let(:member) { opendata_member }
let(:show_path) { "#{node_member.url}#{member.id}/" }
it do
page.driver.browser.with_session("public") do |session|
session.env("HTTP_X_FORWARDED_HOST", site.domain)
visit show_path
expect(page).to have_selector("article#cms-tab-#{member.id}-0")
expect(page).to have_selector("article#cms-tab-#{member.id}-1")
expect(page).to have_selector("article#cms-tab-#{member.id}-2")
within "article#cms-tab-#{member.id}-1" do
click_link "もっと見る"
end
expect(page).to have_selector("section.apps")
end
end
end
describe "show and idea" do
let(:member) { opendata_member }
let(:show_path) { "#{node_member.url}#{member.id}/" }
it do
page.driver.browser.with_session("public") do |session|
session.env("HTTP_X_FORWARDED_HOST", site.domain)
visit show_path
expect(page).to have_selector("article#cms-tab-#{member.id}-0")
expect(page).to have_selector("article#cms-tab-#{member.id}-1")
expect(page).to have_selector("article#cms-tab-#{member.id}-2")
within "article#cms-tab-#{member.id}-2" do
click_link "もっと見る"
end
expect(page).to have_selector("section.ideas")
end
end
end
end
|
shirasagi/opendata
|
spec/models/chorg/main_runner_spec.rb
|
require 'spec_helper'
describe Chorg::MainRunner, dbscope: :example do
let(:root_group) { create(:revision_root_group) }
let(:site) { create(:cms_site, group_ids: [root_group.id]) }
context "with add" do
let(:revision) { create(:revision, site_id: site.id) }
let(:changeset) { create(:add_changeset, revision_id: revision.id) }
subject { described_class.new }
it do
expect(changeset).not_to be_nil
expect { subject.call(site.host, nil, revision.name, 1) }.not_to raise_error
expect(Cms::Group.where(name: changeset.destinations.first["name"]).first).not_to be_nil
end
end
context "with move" do
let(:group) { create(:revision_new_group) }
let(:revision) { create(:revision, site_id: site.id) }
let(:changeset) { create(:move_changeset, revision_id: revision.id, source: group) }
context "with Article::Page" do
let(:page) { create(:revisoin_page, site: site, group: group) }
subject { described_class.new }
it do
# ensure create models
expect(changeset).not_to be_nil
expect(page).not_to be_nil
# execute
expect { subject.call(site.host, nil, revision.name, 1) }.not_to raise_error
expect(Cms::Group.where(name: group.name).first).to be_nil
expect(Cms::Group.where(id: group.id).first.name).to eq changeset.destinations.first["name"]
expect(Cms::Group.where(id: group.id).first.contact_email).to eq changeset.destinations.first["contact_email"]
expect(Cms::Group.where(id: group.id).first.contact_tel).to eq changeset.destinations.first["contact_tel"]
expect(Cms::Group.where(id: group.id).first.contact_fax).to eq changeset.destinations.first["contact_fax"]
# ldap_dn is expected not to be changed.
expect(Cms::Group.where(id: group.id).first.ldap_dn).to eq group.ldap_dn
# check page
save_filename = page.filename
page.reload
expect(page.group_ids).to eq [ group.id ]
expect(page.filename).to eq save_filename
expect(page.contact_group_id).to eq group.id
expect(page.contact_email).to eq changeset.destinations.first["contact_email"]
expect(page.contact_tel).to eq changeset.destinations.first["contact_tel"]
expect(page.contact_fax).to eq changeset.destinations.first["contact_fax"]
end
end
context "with only move name" do
let(:group) { create(:revision_new_group) }
let(:revision) { create(:revision, site_id: site.id) }
let(:changeset) { create(:move_changeset_only_name, revision_id: revision.id, source: group) }
context "with Article::Page" do
let(:page) { create(:revisoin_page, site: site, group: group) }
subject { described_class.new }
it do
# ensure create models
expect(changeset).not_to be_nil
expect(page).not_to be_nil
# execute
expect { subject.call(site.host, nil, revision.name, 1) }.not_to raise_error
expect(Cms::Group.where(name: group.name).first).to be_nil
expect(Cms::Group.where(id: group.id).first.name).to eq changeset.destinations.first["name"]
# these attributes are expected not to be changed.
expect(Cms::Group.where(id: group.id).first.contact_email).to eq group.contact_email
expect(Cms::Group.where(id: group.id).first.contact_tel).to eq group.contact_tel
expect(Cms::Group.where(id: group.id).first.contact_fax).to eq group.contact_fax
expect(Cms::Group.where(id: group.id).first.ldap_dn).to eq group.ldap_dn
# check page
save_filename = page.filename
page.reload
expect(page.group_ids).to eq [ group.id ]
expect(page.filename).to eq save_filename
expect(page.contact_group_id).to eq group.id
expect(page.contact_email).to eq group.contact_email
expect(page.contact_tel).to eq group.contact_tel
expect(page.contact_fax).to eq group.contact_fax
end
end
end
context "with workflow approving Article::Page" do
let(:user1) do
create(:cms_user, name: "#{unique_id}", email: <EMAIL>",
group_ids: [group.id], cms_role_ids: [cms_role.id])
end
let(:user2) do
create(:cms_user, name: "#{unique_id}", email: <EMAIL>",
group_ids: [group.id], cms_role_ids: [cms_role.id])
end
let(:page) do
page = build(:revisoin_page, site: site, group: group, workflow_user_id: user1.id,
workflow_state: "request",
workflow_comment: "",
workflow_approvers: [{level: 1, user_id: user2.id, state: "request", comment: ""}],
workflow_required_counts: [false])
page.cur_site = site
page.save!
page
end
subject { described_class.new }
it do
# ensure create models
expect(changeset).not_to be_nil
expect(page).not_to be_nil
# execute
expect { subject.call(site.host, user1.id, revision.name, 1) }.not_to raise_error
expect(Cms::Group.where(name: group.name).first).to be_nil
expect(Cms::Group.where(id: group.id).first.name).to eq changeset.destinations.first["name"]
# check page
save_filename = page.filename
page.reload
expect(page.group_ids).to eq [ group.id ]
expect(page.filename).to eq save_filename
expect(page.contact_group_id).to eq group.id
expect(page.contact_email).to eq changeset.destinations.first["contact_email"]
expect(page.contact_tel).to eq changeset.destinations.first["contact_tel"]
expect(page.contact_fax).to eq changeset.destinations.first["contact_fax"]
end
end
end
context "with unify" do
context "with Article::Page" do
let(:group1) { create(:revision_new_group) }
let(:group2) { create(:revision_new_group) }
let(:user1) { create(:cms_user, name: "#{unique_id}", email: <EMAIL>", group_ids: [group1.id]) }
let(:user2) { create(:cms_user, name: "#{unique_id}", email: <EMAIL>", group_ids: [group2.id]) }
let(:revision) { create(:revision, site_id: site.id) }
let(:changeset) { create(:unify_changeset, revision_id: revision.id, sources: [group1, group2]) }
let(:page) { create(:revisoin_page, site: site, group: group1) }
subject { described_class.new }
it do
# ensure create models
expect(user1).not_to be_nil
expect(user2).not_to be_nil
expect(changeset).not_to be_nil
expect(page).not_to be_nil
# execute
expect { subject.call(site.host, user1.id, revision.name, 1) }.not_to raise_error
expect(Cms::Group.where(id: group1.id).first).to be_nil
expect(Cms::Group.where(name: group1.name).first).to be_nil
expect(Cms::Group.where(id: group2.id).first).to be_nil
expect(Cms::Group.where(name: group2.name).first).to be_nil
new_group = Cms::Group.where(name: changeset.destinations.first["name"]).first
expect(new_group).not_to be_nil
# check page
page.reload
expect(page.group_ids).to eq [ new_group.id ]
expect(page.contact_group_id).to eq new_group.id
expect(page.contact_email).to eq new_group.contact_email
expect(page.contact_tel).to eq new_group.contact_tel
expect(page.contact_fax).to eq new_group.contact_fax
user1.reload
expect(user1.group_ids).to eq [new_group.id]
user2.reload
expect(user2.group_ids).to eq [new_group.id]
end
end
context "unify to existing group" do
let(:group1) { create(:revision_new_group, contact_email: "<EMAIL>") }
let(:group2) { create(:revision_new_group, contact_email: "<EMAIL>") }
let(:user1) { create(:cms_user, name: "#{unique_id}", email: <EMAIL>", group_ids: [group1.id]) }
let(:user2) { create(:cms_user, name: "#{unique_id}", email: <EMAIL>", group_ids: [group2.id]) }
let(:revision) { create(:revision, site_id: site.id) }
let(:changeset) do
create(:unify_changeset, revision_id: revision.id, sources: [group1, group2], destination: group1)
end
let(:page) { create(:revisoin_page, site: site, group: group1) }
subject { described_class.new }
it do
# ensure create models
expect(user1).not_to be_nil
expect(user2).not_to be_nil
expect(changeset).not_to be_nil
expect(changeset.destinations[0]["name"]).to eq group1.name
expect(changeset.destinations[0]["contact_email"]).to eq group1.contact_email
expect(changeset.destinations[0]["contact_tel"]).to eq group1.contact_tel
expect(changeset.destinations[0]["contact_fax"]).to eq group1.contact_fax
expect(page).not_to be_nil
expect(page.contact_email).to eq "<EMAIL>"
# execute
expect { subject.call(site.host, user1.name, revision.name, 1) }.not_to raise_error
# group1 shoud be exist because group1 is destination_group.
expect(Cms::Group.where(id: group1.id).first).not_to be_nil
expect(Cms::Group.where(name: group1.name).first).not_to be_nil
# group2 shoudn't be exist because group2 is not destination_group.
expect(Cms::Group.where(id: group2.id).first).to be_nil
expect(Cms::Group.where(name: group2.name).first).to be_nil
new_group = Cms::Group.where(name: changeset.destinations.first["name"]).first
expect(new_group.id).to eq group1.id
expect(new_group.name).to eq group1.name
# check page
page.reload
expect(page.group_ids).to eq [ new_group.id ]
expect(page.contact_group_id).to eq new_group.id
expect(page.contact_email).to eq new_group.contact_email
expect(page.contact_email).to eq "<EMAIL>"
expect(page.contact_tel).to eq new_group.contact_tel
expect(page.contact_fax).to eq new_group.contact_fax
user1.reload
expect(user1.group_ids).to eq [new_group.id]
user2.reload
expect(user2.group_ids).to eq [new_group.id]
end
end
end
context "with division" do
context "with Article::Page" do
let(:group0) { create(:revision_new_group) }
let(:group1) { build(:revision_new_group) }
let(:group2) { build(:revision_new_group) }
let(:user) { create(:cms_user, name: "#{unique_id}", email: <EMAIL>", group_ids: [group0.id]) }
let(:revision) { create(:revision, site_id: site.id) }
let(:changeset) do
create(:division_changeset, revision_id: revision.id, source: group0, destinations: [group1, group2])
end
let(:page) { create(:revisoin_page, site: site, group: group0) }
subject { described_class.new }
it do
# ensure create models
expect(user).not_to be_nil
expect(changeset).not_to be_nil
expect(page).not_to be_nil
# execute
expect { subject.call(site.host, user.name, revision.name, 1) }.not_to raise_error
expect(Cms::Group.where(id: group0.id).first).to be_nil
expect(Cms::Group.where(name: group0.name).first).to be_nil
new_group1 = Cms::Group.where(name: changeset.destinations[0]["name"]).first
expect(new_group1).not_to be_nil
new_group2 = Cms::Group.where(name: changeset.destinations[1]["name"]).first
expect(new_group2).not_to be_nil
# check page
page.reload
expect(page.group_ids).to eq [ new_group1.id, new_group2.id ]
expect(page.contact_group_id).to eq new_group1.id
expect(page.contact_email).to eq new_group1.contact_email
expect(page.contact_tel).to eq new_group1.contact_tel
expect(page.contact_fax).to eq new_group1.contact_fax
user.reload
expect(user.group_ids).to eq [ new_group1.id ]
end
end
context "divide from existing group to existing group" do
let(:group1) { create(:revision_new_group) }
let(:group2) { build(:revision_new_group) }
let(:user) { create(:cms_user, name: "#{unique_id}", email: <EMAIL>", group_ids: [group1.id]) }
let(:revision) { create(:revision, site_id: site.id) }
let(:changeset) do
create(:division_changeset, revision_id: revision.id, source: group1, destinations: [group1, group2])
end
let(:page) { create(:revisoin_page, site: site, group: group1) }
subject { described_class.new }
it do
# ensure create models
expect(user).not_to be_nil
expect(changeset).not_to be_nil
expect(page).not_to be_nil
# execute
expect { subject.call(site.host, user.id, revision.name, 1) }.not_to raise_error
expect(Cms::Group.where(id: group1.id).first).not_to be_nil
expect(Cms::Group.where(name: group1.name).first).not_to be_nil
# expect(Cms::Group.where(id: group2.id).first).not_to be_nil
expect(Cms::Group.where(name: group2.name).first).not_to be_nil
new_group1 = Cms::Group.where(name: changeset.destinations[0]["name"]).first
expect(new_group1).not_to be_nil
new_group2 = Cms::Group.where(name: changeset.destinations[1]["name"]).first
expect(new_group2).not_to be_nil
# check page
page.reload
expect(page.group_ids).to eq [ new_group1.id, new_group2.id ]
expect(page.contact_group_id).to eq new_group1.id
expect(page.contact_email).to eq new_group1.contact_email
expect(page.contact_tel).to eq new_group1.contact_tel
expect(page.contact_fax).to eq new_group1.contact_fax
user.reload
expect(user.group_ids).to eq [ new_group1.id ]
end
end
end
context "with delete" do
let(:group) { create(:revision_new_group) }
let(:revision) { create(:revision, site_id: site.id) }
let(:changeset) { create(:delete_changeset, revision_id: revision.id, source: group) }
subject { described_class.new }
it do
# ensure create models
expect(changeset).not_to be_nil
# execute
expect { subject.call(site.host, nil, revision.name, 1) }.not_to raise_error
expect(Cms::Group.where(id: group.id).first).to be_nil
end
end
end
|
shirasagi/opendata
|
spec/models/opendata/license_spec.rb
|
require 'spec_helper'
describe Opendata::License, dbscope: :example do
context "check attributes with typical url resource" do
let(:site) { cms_site }
let(:license_logo_file_path) { Rails.root.join("spec", "fixtures", "ss", "logo.png") }
let(:license_logo_file) { Fs::UploadedFile.create_from_file(license_logo_file_path, basename: "spec") }
subject { create(:opendata_license, site: site, file: license_logo_file) }
its(:state_options) { is_expected.to include %w(非公開 closed) }
end
describe ".public" do
it { expect(described_class.public.selector.to_h).to include("state" => "public") }
end
describe ".search" do
it { expect(described_class.search(nil).selector.to_h).to be_empty }
it do
expect(described_class.search(keyword: "キーワード").selector.to_h).to \
include("$and" => include("$or" => include("name" => /キーワード/i)))
end
it do
expect(described_class.search(keyword: "()[]{}.?+*|\\").selector.to_h).to \
include("$and" => include("$or" => include("name" => /\(\)\[\]\{\}\.\?\+\*\|\\/i)))
end
end
end
|
shirasagi/opendata
|
spec/features/opendata/dataset/dataset_groups_spec.rb
|
<filename>spec/features/opendata/dataset/dataset_groups_spec.rb<gh_stars>1-10
require 'spec_helper'
describe "opendata_dataset_groups", type: :feature, dbscope: :example do
let(:site) { cms_site }
let(:node) { create_once :opendata_node_dataset, name: "opendata_dataset" }
let(:index_path) { opendata_dataset_groups_path site.host, node }
let(:new_path) { new_opendata_dataset_group_path site.host, node }
it "without login" do
visit index_path
expect(current_path).to eq sns_login_path
end
it "without auth" do
login_ss_user
visit index_path
expect(status_code).to eq 403
end
context "with auth" do
before { login_cms_user }
describe "#index" do
it do
visit index_path
expect(current_path).not_to eq sns_login_path
end
end
describe "#new" do
it do
category_folder = create_once(:cms_node_node, basename: "category")
create_once(
:opendata_node_category,
basename: "#{category_folder.filename}/opendata_category1",
depth: category_folder.depth + 1)
visit new_path
within "form#item-form" do
fill_in "item[name]", with: "sample"
all("input[type=checkbox][id^='item_category_ids']").each { |c| check c[:id] }
click_button "保存"
end
expect(status_code).to eq 200
expect(current_path).not_to eq new_path
expect(page).not_to have_css("form#item-form")
end
end
describe "#show" do
let(:category_folder) { create_once(:cms_node_node, basename: "category") }
let(:category) do
create_once(
:opendata_node_category,
basename: "#{category_folder.filename}/opendata_category1",
depth: category_folder.depth + 1)
end
let(:item) { create(:opendata_dataset_group, site: site, category_ids: [ category.id ]) }
let(:show_path) { opendata_dataset_group_path site.host, node, item }
it do
visit show_path
expect(status_code).to eq 200
expect(current_path).not_to eq sns_login_path
end
end
describe "#edit" do
let(:category_folder) { create_once(:cms_node_node, basename: "category") }
let(:category) do
create_once(
:opendata_node_category,
basename: "#{category_folder.filename}/opendata_category1",
depth: category_folder.depth + 1)
end
let(:item) { create(:opendata_dataset_group, site: site, category_ids: [ category.id ]) }
let(:edit_path) { edit_opendata_dataset_group_path site.host, node, item }
it do
visit edit_path
within "form#item-form" do
fill_in "item[name]", with: "modify"
click_button "保存"
end
expect(current_path).not_to eq sns_login_path
expect(page).not_to have_css("form#item-form")
end
end
describe "#delete" do
let(:category_folder) { create_once(:cms_node_node, basename: "category") }
let(:category) do
create_once(
:opendata_node_category,
basename: "#{category_folder.filename}/opendata_category1",
depth: category_folder.depth + 1)
end
let(:item) { create(:opendata_dataset_group, site: site, category_ids: [ category.id ]) }
let(:delete_path) { delete_opendata_dataset_group_path site.host, node, item }
it do
visit delete_path
within "form" do
click_button "削除"
end
expect(current_path).to eq index_path
end
end
end
end
|
shirasagi/opendata
|
config/routes/opendata/idea/routes.rb
|
SS::Application.routes.draw do
Opendata::Initializer
concern :deletion do
get :delete, on: :member
end
content "opendata" do
resources :ideas, concerns: :deletion, module: :idea do
resources :comments, concerns: :deletion
end
resources :idea_categories, concerns: :deletion, module: :idea
resources :search_ideas, concerns: :deletion, module: :idea
end
node "opendata" do
get "idea_category/" => "public#index", cell: "nodes/idea/idea_category"
get "idea_category/rss.xml" => "public#rss", cell: "nodes/idea/idea_category"
get "idea_category/:name/" => "public#index", cell: "nodes/idea/idea_category"
get "idea_category/:name/rss.xml" => "public#rss", cell: "nodes/idea/idea_category"
# get "idea_category/:name/areas" => "public#index_areas", cell: "nodes/idea/idea_category"
# get "idea_category/:name/tags" => "public#index_tags", cell: "nodes/idea/idea_category"
get "idea/(index.:format)" => "public#index", cell: "nodes/idea/idea"
get "idea/rss.xml" => "public#rss", cell: "nodes/idea/idea"
get "idea/areas" => "public#index_areas", cell: "nodes/idea/idea"
get "idea/tags" => "public#index_tags", cell: "nodes/idea/idea"
get "idea/:idea/point.:format" => "public#show_point", cell: "nodes/idea/idea", format: false
post "idea/:idea/point.:format" => "public#add_point", cell: "nodes/idea/idea", format: false
get "idea/:idea/point/members.html" => "public#point_members", cell: "nodes/idea/idea", format: false
get "idea/:idea/comment/show.:format" => "public#index", cell: "nodes/idea/comment", format: false
post "idea/:idea/comment/add.:format" => "public#add", cell: "nodes/idea/comment", format: false
post "idea/:idea/comment/delete.:format" => "public#delete", cell: "nodes/idea/comment", format: false
get "idea/:idea/dataset/show.:format" => "public#show_dataset", cell: "nodes/idea/idea", format: false
get "idea/:idea/app/show.:format" => "public#show_app", cell: "nodes/idea/idea", format: false
match "search_idea/(index.:format)" => "public#index", cell: "nodes/idea/search_idea", via: [:get, :post]
get "search_idea/rss.xml" => "public#rss", cell: "nodes/idea/search_idea"
end
part "opendata" do
get "idea" => "public#index", cell: "parts/idea/idea"
end
page "opendata" do
get "idea/:filename.:format" => "public#index", cell: "pages/idea/idea"
end
end
|
shirasagi/opendata
|
app/models/concerns/cms/addon/body.rb
|
<gh_stars>1-10
module Cms::Addon
module Body
extend ActiveSupport::Concern
extend SS::Addon
included do
field :html, type: String, metadata: { form: :text }
field :markdown, type: String
permit_params :html, :markdown
validate :convert_markdown, if: -> { SS.config.cms.html_editor == "markdown" }
end
public
def markdown2html
::Redcarpet::Markdown.new(Redcarpet::Render::HTML).render(markdown)
end
private
def convert_markdown
self.html = markdown2html
end
end
end
|
shirasagi/opendata
|
app/models/concerns/ads/addon/page_list.rb
|
<reponame>shirasagi/opendata<gh_stars>1-10
module Ads::Addon
module PageList
extend ActiveSupport::Concern
extend SS::Addon
included do
field :link_action, type: String
field :link_target, type: String
field :sort, type: String
field :with_category, type: String
field :upper_html, type: String
field :lower_html, type: String
permit_params :link_action, :link_target, :sort, :with_category, :upper_html, :lower_html
end
public
def link_action_options
[
[I18n.t('ads.options.link_action.cushion'), ''],
[I18n.t('ads.options.link_action.direct'), 'direct'],
]
end
def link_target_options
[
[I18n.t('ads.options.link_target.self'), ''],
[I18n.t('ads.options.link_target.blank'), 'blank'],
]
end
def sort_options
[
[I18n.t('ads.options.sort.order'), 'order'],
[I18n.t('ads.options.sort.random'), 'random'],
]
end
def with_category_options
[
[I18n.t("views.options.state.enabled"), "enabled"],
[I18n.t("views.options.state.disabled"), "disabled"],
]
end
def sort_hash
if sort == "random"
{ random: 1 }
else
{ order: 1 }
end
end
end
end
|
shirasagi/opendata
|
app/models/sys/group.rb
|
class Sys::Group
include SS::Model::Group
include Sys::Permission
include Contact::Addon::Group
set_permission_name "sys_users", :edit
attr_accessor :sys_role_ids
permit_params :sys_role_ids
public
def users
SS::User.in(group_ids: id)
end
end
|
shirasagi/opendata
|
spec/features/opendata/agents/parts/dataset/dataset_group_spec.rb
|
require 'spec_helper'
describe "opendata_agents_nodes_dataset_group", dbscope: :example do
let(:site) { cms_site }
let!(:category) { create :opendata_node_category, basename: "bunya/kurashi" }
let!(:dataset_group) { create :opendata_dataset_group, categories: [ category ] }
let(:node) { create :opendata_node_dataset_category }
let(:part) { create :opendata_part_dataset_group, node: node }
before do
create :opendata_node_search_dataset, basename: "dataset/search"
create :opendata_node_search_dataset_group
end
let(:index_url) { ::URI.parse "http://#{site.domain}#{part.url}" }
describe "#index" do
it do
visit "#{index_url}?ref=/#{node.filename}"
expect(status_code).to eq 200
expect(current_path).to eq index_url.path
expect(page).to have_link dataset_group.name
end
end
end
|
shirasagi/opendata
|
lib/ldap/user.rb
|
<reponame>shirasagi/opendata<filename>lib/ldap/user.rb
class Ldap::User < Ldap::Entry
def initialize(connection, entry)
super(connection, entry)
end
def authenticate(password)
config = @connection.config.to_h.merge({ username: dn, password: password })
new_connection = Ldap::Connection.connect(config) rescue nil
new_connection.present?
end
end
class Ldap::InetOrgPerson < Ldap::User
public_class_method :new
def name
value(:cn)
end
def uid
value(:uid)
end
def email
value(:mail)
end
def self.support?(object_classes)
object_classes.include?("inetOrgPerson")
end
def self.filter
Net::LDAP::Filter.construct("(objectClass=inetOrgPerson)")
end
end
# class Ldap::PosixAccount < Ldap::User
# public_class_method :new
#
# def name
# value(:cn)
# end
#
# def uid
# value(:uid)
# end
#
# def email
# value(:mail)
# end
#
# def self.support?(object_classes)
# object_classes.include?("posixAccount")
# end
#
# def self.filter
# Net::LDAP::Filter.construct("(objectClass=posixAccount)")
# end
# end
class Ldap::User
private_class_method :new
# CONCRETE_CLASSES = [ Ldap::InetOrgPerson, Ldap::PosixAccount ].freeze
CONCRETE_CLASSES = [ Ldap::InetOrgPerson ].freeze
DEFAULT_FILTER = CONCRETE_CLASSES.map { |c| c.filter }.reduce { |a, e| a | e }
def self.create(connection, entry)
object_classes = Ldap::Entry.normalize(entry[:objectClass])
CONCRETE_CLASSES.each do |c|
return c.new(connection, entry) if c.support?(object_classes)
end
Rails.logger.info("unknown object class: #{object_classes}")
nil
end
end
|
shirasagi/opendata
|
app/controllers/application_controller.rb
|
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 -> { FileUtils.touch "#{Rails.root}/Gemfile" } if Rails.env.to_s == "development"
before_action :set_cache_buster
public
def t(key, opts = {})
opts[:scope] = [:views] if key !~ /\./ && !opts[:scope]
I18n.t key, opts.merge(default: key.to_s.humanize)
end
def new_agent(controller_name)
agent = SS::Agent.new controller_name
agent.controller.params = params
agent.controller.request = request
agent.controller.instance_variable_set :@controller, self
agent
end
def render_agent(controller_name, action)
new_agent(controller_name).render(action)
end
def invoke_agent(controller_name, action)
new_agent(controller_name).invoke(action)
end
private
def remote_addr
request.env["HTTP_X_REAL_IP"] || request.remote_addr
end
def browser
require "browser"
Browser.new(request.user_agent, accept_language: request.accept_language)
end
# Accepts the request for Cross-Origin Resource Sharing.
# @return boolean
def accept_cors_request
if request.env["HTTP_ORIGIN"].present?
headers["Access-Control-Allow-Origin"] = request.env["HTTP_ORIGIN"]
headers["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
headers["Access-Control-Allow-Headers"] = "Content-Type, Origin, Accept"
end
if request.request_method == "OPTIONS"
headers["Access-Control-Max-Age"] = "86400"
headers["Content-Length"] = "0"
headers["Content-Type"] = "text/plain"
render text: ""
end
end
def set_cache_buster
if request.xhr?
response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "-1"
end
end
end
|
shirasagi/opendata
|
app/controllers/sns/login_controller.rb
|
<reponame>shirasagi/opendata
class Sns::LoginController < ApplicationController
include Sns::BaseFilter
protect_from_forgery except: :remote_login
skip_filter :logged_in?, only: [:login, :remote_login]
navi_view nil
private
def get_params
params.require(:item).permit(:uid, :email, :password)
end
public
def login
if !request.post?
# retrieve parameters from get parameter. this is bookmark support.
@item = SS::User.new email: params[:email]
return
end
safe_params = get_params
email_or_uid = safe_params[:email].presence || safe_params[:uid]
password = safe_params[:password]
@item = SS::User.authenticate(email_or_uid, password)
unless @item
@item = SS::User.new email: email_or_uid
@error = t "sns.errors.invalid_login"
return
end
if params[:ref].blank? || [sns_login_path, sns_mypage_path].index(params[:ref])
return set_user @item, session: true, redirect: true, password: password
end
set_user @item, session: true, password: password
render :redirect
end
def remote_login
raise "404" unless SS::config.sns.remote_login
login
render :login if response.body.blank?
end
def logout
put_history_log
unset_user redirect: true
end
end
|
shirasagi/opendata
|
app/models/chorg/revision.rb
|
class Chorg::Revision
extend SS::Translation
include SS::Document
include SS::Reference::Site
include Cms::SitePermission
include Voice::Lockable
set_permission_name "cms_users", :edit
attr_accessor :add_newly_created_group_to_site
seqid :id
field :name, type: String
has_many :changesets, class_name: "Chorg::Changeset", dependent: :destroy
field :job_ids, type: Array
permit_params :name, :changesets, :add_newly_created_group_to_site
validates :name, presence: true, length: { maximum: 80 }, uniqueness: { scope: :site_id }
def add_changesets
changesets.select { |e| e.type == Chorg::Changeset::TYPE_ADD }
end
def move_changesets
changesets.select { |e| e.type == Chorg::Changeset::TYPE_MOVE }
end
def unify_changesets
changesets.select { |e| e.type == Chorg::Changeset::TYPE_UNIFY }
end
def division_changesets
changesets.select { |e| e.type == Chorg::Changeset::TYPE_DIVISION }
end
def delete_changesets
changesets.select { |e| e.type == Chorg::Changeset::TYPE_DELETE }
end
end
|
shirasagi/opendata
|
app/controllers/cms/preview_controller.rb
|
class Cms::PreviewController < ApplicationController
include Cms::BaseFilter
include Cms::PublicFilter
include Fs::FileFilter
before_action :set_group
before_action :set_path_with_preview, prepend: true
after_action :render_preview, if: ->{ @file =~ /\.html$/ }
after_action :render_mobile, if: ->{ mobile_path? }
private
def set_site
@cur_site = SS::Site.find_by host: params[:site]
@preview = true
end
def set_path_with_preview
@cur_path ||= request.env["REQUEST_PATH"]
@cur_path.sub!(/^#{cms_preview_path}(\d+)?/, "")
@cur_path = "index.html" if @cur_path.blank?
@cur_path = URI.decode(@cur_path)
@cur_date = params[:preview_date].present? ? params[:preview_date].in_time_zone : Time.zone.now
end
def x_sendfile(file = @file)
return if file =~ /\.(ht|x)ml$/
return if file =~ /\.part\.json$/
super
return if response.body.present?
if @cur_path =~ /^\/fs\//
path = @cur_path.sub("/thumb/", "/")
filename = ::File.basename(path)
id = ::File.dirname(path).sub("/fs/", "").sub("/_", "").gsub("/", "")
@item = SS::File.find_by id: id, filename: filename
if @cur_path =~ /\/thumb\//
if @item.thumb
@item = @item.thumb
else
@thumb_width = params[:width]
@thumb_height = params[:height]
end
end
if @thumb_width && @thumb_height
send_thumb @item.read, type: @item.content_type, filename: @item.filename,
disposition: :inline, width: @thumb_width, height: @thumb_height
return
else
send_file @item.path, type: @item.content_type, filename: @item.filename,
disposition: :inline, x_sendfile: true
return
end
end
#raise "404" unless Fs.exists?(file)
end
def render_preview
preview_url = cms_preview_path preview_date: params[:preview_date]
body = response.body.force_encoding("utf-8")
body.gsub!(/(href|src)=".*?"/) do |m|
url = m.match(/.*?="(.*?)"/)[1]
if url =~ /^\/(assets|assets-dev)\//
m
elsif url =~ /^\/(?!\/)/
m.sub(/="/, "=\"#{preview_url}")
else
m
end
end
s = []
s << '$(function(){'
s << 'SS_Preview.mobile_path = "' + SS.config.mobile.location + '";'
s << 'SS_Preview.render();'
s << '});'
h = []
h << view_context.stylesheet_link_tag("cms/preview")
h << '<link href="/assets/css/datetimepicker/jquery.datetimepicker.css" rel="stylesheet" />'
h << '<link href="/assets/css/colorbox/colorbox.css" rel="stylesheet" />'
h << '<script src="/assets/cms/public.js"></script>'
h << '<script src="/assets/js/jquery.datetimepicker.js"></script>'
h << '<script src="/assets/js/jquery.colorbox.js"></script>'
h << '<script>' + s.join + '</script>'
h << '<div id="ss-preview">'
h << '<input type="text" class="date" value="' + @cur_date.strftime("%Y/%m/%d %H:%M") + '" />'
h << '<input type="button" class="preview" value="' + t("views.links.pc") + '">'
h << '<input type="button" class="mobile" value=' + t("views.links.mobile") + '>'
h << '</div>'
body.sub!("</body>", h.join("\n") + "</body>")
response.body = body
end
end
|
shirasagi/opendata
|
app/helpers/ss/editor_helper.rb
|
<filename>app/helpers/ss/editor_helper.rb
module SS::EditorHelper
CODE_EXT_MODES = {
html: :htmlmixed,
scss: :css,
js: :javascript,
coffee: :coffeescript,
}
CODE_MODE_FILES = {
htmlmixed: %w(xml javascript css vbscript htmlmixed),
}
def code_editor(elem, opts = {})
mode = opts[:mode].to_s.presence
mode ||= opts[:filename].sub(/.*\./, "") if opts[:filename]
mode = CODE_EXT_MODES[mode.to_sym] if mode && CODE_EXT_MODES[mode.to_sym]
mode_path = "/assets/js/codemirror/mode"
mode_file = "#{Rails.public_path}#{mode_path}"
mode = nil unless File.exists?("#{mode_file}/#{mode}/#{mode}.js") if mode
controller.stylesheet "/assets/css/codemirror/codemirror.css"
controller.javascript "/assets/js/codemirror/codemirror.js"
if mode
(CODE_MODE_FILES[mode.to_sym] || [mode]).each do |m|
controller.javascript "#{mode_path}/#{m}/#{m}.js"
end
end
editor_opts = {}
editor_opts[:mode] = mode if mode.present?
editor_opts[:readOnly] = true if opts[:readonly]
editor_opts[:lineNumbers] = true
jquery do
"Cms_Editor_CodeMirror.render('#{elem}', #{editor_opts.to_json});".html_safe
end
end
def html_editor(elem, opts = {})
case SS.config.cms.html_editor
when "ckeditor"
html_editor_ckeditor(elem, opts)
when "tinymce"
html_editor_tinymce(elem, opts)
when "markdown"
html_editor_markdown(elem, opts)
end
end
def html_editor_ckeditor(elem, opts = {})
controller.javascript "/assets/js/ckeditor/ckeditor.js"
controller.javascript "/assets/js/ckeditor/adapters/jquery.js"
opts = { extraPlugins: "", removePlugins: "" }.merge(opts)
if opts[:readonly]
opts[:removePlugins] << ",toolbar"
#opts[:removePlugins] << ",resize"
#opts[:extraPlugins] << ",autogrow"
opts[:readOnly] = true
opts.delete :readonly
end
opts[:extraPlugins] << ",templates,justify"
#opts[:enterMode] = 2 #BR
#opts[:shiftEnterMode] = 1 #P
opts[:allowedContent] = true
opts[:height] ||= "360px"
opts[:templates] = 'shirasagi'
opts[:templates_files] = [ "#{template_cms_editor_templates_path}.js?_=#{Time.zone.now.to_i}" ]
jquery do
"Cms_Editor_CKEditor.render('#{elem}', #{opts.to_json});".html_safe
end
end
def html_editor_tinymce(elem, opts = {})
controller.javascript "/assets/js/tinymce/tinymce.min.js"
editor_opts = {}
editor_opts[:selector] = elem
editor_opts[:language] = "ja"
if opts[:readonly]
editor_opts[:readonly] = true
editor_opts[:plugins] = []
editor_opts[:toolbar] = false
editor_opts[:menubar] = false
else
editor_opts[:plugins] = [
"advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker",
"searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
"save table contextmenu directionality emoticons template paste textcolor"
]
editor_opts[:toolbar] = "insertfile undo redo | styleselect | bold italic | forecolor backcolor" \
" | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media"
# editor_opts[:templates] = [ { title: 'Some title 1', description: 'Some desc 1', content: 'My content' } ]
editor_opts[:templates] = "#{template_cms_editor_templates_path}.json?_=#{Time.zone.now.to_i}"
end
jquery do
"Cms_Editor_TinyMCE.render('#{elem}', #{editor_opts.to_json});".html_safe
end
end
def html_editor_markdown(elem, opts = {})
end
end
|
shirasagi/opendata
|
app/controllers/sns/auth_token_controller.rb
|
class Sns::AuthTokenController < ApplicationController
public
def index
@item = form_authenticity_token
response.headers['X-CSRF-Token'] = @item
respond_to do |format|
format.html do
response.headers['Content-Type'] = "text/plain"
render layout: false
end
format.json { render }
end
end
end
|
shirasagi/opendata
|
spec/features/workflow/search_approvers_spec.rb
|
require 'spec_helper'
describe "workflow_search_approvers" do
subject(:site) { cms_site }
subject(:user) { cms_user }
subject(:group) { cms_group }
subject(:index_path) { workflow_search_approvers_path site.host }
it "without login" do
visit index_path
expect(current_path).to eq sns_login_path
end
it "without auth" do
login_ss_user
visit index_path
expect(status_code).to eq 403
end
context "with auth" do
before { login_cms_user }
it "#index" do
visit index_path
# save_and_open_page
# print page.html
within("form.search") do
expect(all("option").reduce([]) { |a, e| a << e.value }).to include "#{group.id}"
end
within("table.index") do
expect(find("a.select-item").text).to eq "#{user.long_name}"
end
expect(current_path).not_to eq sns_login_path
end
end
end
|
shirasagi/opendata
|
app/models/concerns/rss/addon/import.rb
|
module Rss::Addon
module Import
extend ActiveSupport::Concern
extend SS::Addon
RSS_REFRESH_METHOD_MANUAL = 'manual'.freeze
RSS_REFRESH_METHOD_AUTO = 'auto'.freeze
RSS_REFRESH_METHODS = [ RSS_REFRESH_METHOD_MANUAL, RSS_REFRESH_METHOD_AUTO ].freeze
included do
field :rss_url, type: String
field :rss_max_docs, type: Integer
field :rss_refresh_method, type: String
permit_params :rss_url, :rss_max_docs, :rss_refresh_method
end
public
def rss_refresh_method_options
RSS_REFRESH_METHODS.map { |m| [ I18n.t("rss.options.rss_refresh_method.#{m}"), m ] }.to_a
end
end
end
|
shirasagi/opendata
|
app/controllers/sns/mypage_controller.rb
|
<reponame>shirasagi/opendata
class Sns::MypageController < ApplicationController
include Sns::BaseFilter
public
def index
#mypage
@sites = []
SS::Site.each do |site|
if @cur_user.groups.in(name: site.groups.pluck(:name).map{ |name| /^#{Regexp.escape(name)}(\/|$)/ } ).present?
@sites << site
end
end
end
end
|
shirasagi/opendata
|
spec/models/opendata/resource_spec.rb
|
require 'spec_helper'
describe Opendata::Resource, dbscope: :example do
let(:site) { cms_site }
let!(:node_search_dataset) { create(:opendata_node_search_dataset) }
let(:node) { create(:opendata_node_dataset) }
let(:dataset) { create(:opendata_dataset, node: node) }
let(:license_logo_file) { upload_file(Rails.root.join("spec", "fixtures", "ss", "logo.png")) }
let(:license) { create(:opendata_license, site: site, file: license_logo_file) }
let(:content_type) { "application/vnd.ms-excel" }
def upload_file(file, content_type = nil)
uploaded_file = Fs::UploadedFile.create_from_file(file, basename: "spec")
uploaded_file.content_type = content_type || "application/octet-stream"
uploaded_file
end
describe "#parse_tsv" do
context "when shift_jis csv is given" do
let(:file) { Rails.root.join("spec", "fixtures", "opendata", "shift_jis.csv") }
subject { dataset.resources.new(attributes_for(:opendata_resource)) }
before do
subject.in_file = upload_file(file, content_type)
subject.license_id = license.id
subject.save!
subject.in_file.close
end
it do
csv = subject.parse_tsv
expect(csv).not_to be_nil
expect(csv.length).to eq 3
expect(csv[0]).to eq %w(ヘッダー 値)
expect(csv[1]).to eq %w(品川 483901)
expect(csv[2]).to eq %w(新宿 43901)
end
end
context "when euc-jp csv is given" do
let(:file) { Rails.root.join("spec", "fixtures", "opendata", "euc-jp.csv") }
subject { dataset.resources.new(attributes_for(:opendata_resource)) }
before do
subject.in_file = upload_file(file, content_type)
subject.license_id = license.id
subject.save!
end
it do
csv = subject.parse_tsv
expect(csv).not_to be_nil
expect(csv.length).to eq 3
expect(csv[0]).to eq %w(ヘッダー 値)
expect(csv[1]).to eq %w(品川 483901)
expect(csv[2]).to eq %w(新宿 43901)
end
end
context "when utf-8 csv is given" do
let(:file) { Rails.root.join("spec", "fixtures", "opendata", "utf-8.csv") }
subject { dataset.resources.new(attributes_for(:opendata_resource)) }
before do
subject.in_file = upload_file(file, content_type)
subject.license_id = license.id
subject.save!
end
it do
csv = subject.parse_tsv
expect(csv).not_to be_nil
expect(csv.length).to eq 3
expect(csv[0]).to eq %w(ヘッダー 値)
expect(csv[1]).to eq %w(品川 483901)
expect(csv[2]).to eq %w(新宿 43901)
end
end
end
describe ".allowed?" do
it { expect(described_class.allowed?(:edit, nil)).to be_truthy }
end
describe ".allow" do
it { expect(described_class.allow(:edit, nil)).to be_truthy }
end
describe ".format_options" do
it { expect(described_class.format_options).to include "AVI" }
end
describe ".search" do
it { expect(described_class.search(keyword: "keyword_b633").selector.to_h).to include("name" => /keyword_b633/) }
it { expect(described_class.search(format: "csv").selector.to_h).to include("format" => "CSV") }
it { expect(described_class.search(xxxx: "xxxxx").selector.to_h).to be_empty }
end
context "ttl file", fuseki: true do
let(:file) { Rails.root.join("spec", "fixtures", "opendata", "test-1.ttl") }
let(:content_type) { "application/octet-stream" }
subject { dataset.resources.new(attributes_for(:opendata_resource)) }
before do
subject.in_file = upload_file(file, content_type)
subject.license_id = license.id
end
after do
subject.in_file.close
end
context "when ttl file is succeeded to send to fuseki server", fuseki: true do
before do
create(:opendata_node_sparql)
end
it do
allow(Opendata::Sparql).to receive(:clear).and_return(nil)
allow(Opendata::Sparql).to receive(:save).and_return(true)
expect { subject.save! }.not_to raise_error
expect(subject.rdf_iri).to eq subject.graph_name
expect(subject.rdf_error).to be_nil
end
end
context "when ttl file is failed to send to fuseki server", fuseki: true do
before do
create(:opendata_node_sparql)
end
it do
allow(Opendata::Sparql).to receive(:clear).and_return(nil)
allow(Opendata::Sparql).to receive(:save).and_raise("error from mock/stub")
expect { subject.save! }.not_to raise_error
expect(subject.rdf_iri).to be_nil
expect(subject.rdf_error).to eq I18n.t("opendata.errors.messages.invalid_rdf")
end
end
end
context "when japanese filename is uploaded" do
let(:tmpdir) { Dir.mktmpdir }
let(:file) do
File.open("#{tmpdir}/index - コピー.html", "w") do |fp|
fp.puts "<html></html>"
end
"#{tmpdir}/index - コピー.html"
end
subject { dataset.resources.new(attributes_for(:opendata_resource)) }
before do
subject.in_file = upload_file(file, content_type)
subject.license_id = license.id
subject.save!
end
after do
::FileUtils.rm_rf tmpdir
end
its(:url) { is_expected.to end_with("/#{URI.escape("index - コピー.html")}")}
its(:full_url) { is_expected.to end_with("/#{URI.escape("index - コピー.html")}")}
end
end
|
shirasagi/opendata
|
app/controllers/opendata/agents/tasks/node/apps_controller.rb
|
<reponame>shirasagi/opendata<gh_stars>1-10
class Opendata::Agents::Tasks::Node::AppsController < ApplicationController
include Cms::PublicFilter::Node
public
def generate
generate_node @node
end
end
|
shirasagi/opendata
|
app/models/opendata/license.rb
|
class Opendata::License
include SS::Document
include SS::Reference::User
include SS::Reference::Site
include SS::Relation::File
include Cms::Addon::GroupPermission
set_permission_name :opendata_datasets
seqid :id
field :state, type: String, default: "public"
field :name, type: String
field :related_url, type: String
field :order, type: Integer, default: 0
belongs_to_file :file
permit_params :state, :name, :related_url, :order, file_ids: []
validates :state, presence: true
validates :name, presence: true, length: { maximum: 80 }
validates :in_file, presence: true, if: ->{ file_id.blank? }
def state_options
[[I18n.t("opendata.state_options.public"), "public"], [I18n.t("opendata.state_options.closed"), "closed"]]
end
class << self
public
def public
where(state: "public")
end
def search(params)
criteria = self.where({})
return criteria if params.blank?
criteria = criteria.keyword_in params[:keyword], :name if params[:keyword].present?
criteria
end
end
end
|
shirasagi/opendata
|
app/controllers/faq/agents/parts/search_controller.rb
|
<reponame>shirasagi/opendata
class Faq::Agents::Parts::SearchController < ApplicationController
include Cms::PartFilter::View
include Cms::PublicFilter::Layout
include Mobile::PublicFilter
helper Cms::ListHelper
public
def index
@search_node = @cur_part.search_node.present? ? @cur_part.search_node : @cur_part.parent
@url = mobile_path? ? "#{SS.config.mobile.location}#{@search_node.url}" : @search_node.url
@search_node.blank? ? "" : render
end
end
|
shirasagi/opendata
|
app/models/opendata/appfile.rb
|
<reponame>shirasagi/opendata<filename>app/models/opendata/appfile.rb
class Opendata::Appfile
include SS::Document
include SS::Relation::File
include Opendata::TsvParseable
include Opendata::AllowableAny
include Opendata::Common
attr_accessor :workflow, :status
seqid :id
field :filename, type: String
field :text, type: String
field :format, type: String
embedded_in :app, class_name: "Opendata::App", inverse_of: :appfile
belongs_to_file :file
permit_params :text
validates :in_file, presence: true, if: ->{ file_id.blank? }
validates :filename, uniqueness: true
validate :validate_appfile
before_validation :set_filename, if: ->{ in_file.present? }
after_save :save_app
after_destroy -> { app.save(validate: false) }
public
def url
get_app_url(app, "/appfile/#{id}/#{URI.escape(filename)}")
end
def full_url
get_app_full_url(app, "/appfile/#{id}/#{URI.escape(filename)}")
end
def content_url
get_app_full_url(app, "/appfile/#{id}/content.html")
end
def json_url
get_app_full_url(app, "/appfile/#{id}/json.html")
end
def path
file ? file.path : nil
end
def content_type
file ? file.content_type : nil
end
def size
file ? file.size : nil
end
private
def set_filename
self.filename = in_file.original_filename
self.format = filename.sub(/.*\./, "").upcase
end
def validate_appfile
if self.app.appurl.present?
errors.clear
errors.add :file_id, I18n.t("opendata.errors.messages.validate_appfile")
return
end
end
def save_app
self.workflow ||= {}
app.cur_site = app.site
app.apply_status(status, workflow) if status.present?
app.released ||= Time.zone.now
app.save(validate: false)
end
class << self
public
def search(params)
criteria = self.where({})
return criteria if params.blank?
criteria = criteria.where(filename: /#{params[:keyword]}/) if params[:keyword].present?
criteria
end
end
end
|
shirasagi/opendata
|
app/models/key_visual/image.rb
|
<reponame>shirasagi/opendata
class KeyVisual::Image
include Cms::Model::Page
include SS::Relation::File
include Cms::Addon::Release
include Cms::Addon::ReleasePlan
include Cms::Addon::GroupPermission
include History::Addon::Backup
set_permission_name "key_visual_images"
field :link_url, type: String
belongs_to_file :file
validates :in_file, presence: true, if: -> { file_id.blank? }
before_save :seq_filename, if: ->{ basename.blank? }
permit_params :link_url
default_scope ->{ where(route: "key_visual/image") }
public
def serve_static_file?
false
end
private
def validate_filename
@basename.blank? ? nil : super
end
def seq_filename
self.filename = dirname ? "#{dirname}#{id}.html" : "#{id}.html"
end
end
|
shirasagi/opendata
|
spec/features/opendata/agents/parts/dataset/dataset_spec.rb
|
<filename>spec/features/opendata/agents/parts/dataset/dataset_spec.rb
require 'spec_helper'
describe "opendata_agents_nodes_dataset", dbscope: :example do
let(:site) { cms_site }
let!(:node_category) { create :opendata_node_category, basename: "bunya/kurashi" }
let!(:node_search_dataset) { create :opendata_node_search_dataset, basename: "dataset/search" }
let!(:node_search_dataset_group) { create :opendata_node_search_dataset_group }
let!(:node_dataset) { create(:opendata_node_dataset) }
let!(:page_dataset) { create(:opendata_dataset, node: node_dataset) }
let(:part) { create :opendata_part_dataset, sort: 'attention' }
let(:index_url) { ::URI.parse "http://#{site.domain}#{part.url}" }
describe "#index" do
it do
visit "#{index_url}"
expect(status_code).to eq 200
expect(current_path).to eq index_url.path
within "div.pages" do
expect(page).to have_content(page_dataset.name)
end
expect(page).not_to have_css("nav.feed")
end
end
end
|
shirasagi/opendata
|
db/seeds/users/load.rb
|
<filename>db/seeds/users/load.rb
Dir.chdir @root = File.dirname(__FILE__)
@site = SS::Site.find_by host: ENV["site"]
## -------------------------------------
puts "# groups"
def save_group(data)
puts data[:name]
cond = { name: data[:name] }
item = SS::Group.find_or_create_by cond
item.update_attributes! data
item
end
g1_00 = save_group name: "シラサギ市", order: 10
g1_10 = save_group name: "シラサギ市/企画政策部", order: 20
g1_11 = save_group name: "シラサギ市/企画政策部/政策課", order: 30
g1_12 = save_group name: "シラサギ市/企画政策部/広報課", order: 40
g1_20 = save_group name: "シラサギ市/危機管理部", order: 50
g1_21 = save_group name: "シラサギ市/危機管理部/管理課", order: 60
g1_22 = save_group name: "シラサギ市/危機管理部/防災課", order: 70
@site.add_to_set group_ids: g1_00.id
## -------------------------------------
puts "# roles"
def save_cms_role(data)
puts data[:name]
cond = { name: data[:name], site_id: @site.id }
item = Cms::Role.find_or_create_by cond
item.update data.merge site_id: @site.id
item
end
role1 = save_cms_role name: "サイト管理者", permission_level: 3,
permissions: Cms::Role.permission_names
role2 = save_cms_role name: "記事編集権限", permission_level: 1,
permissions: %w(
read_private_article_pages edit_private_article_pages
delete_private_article_pages read_other_article_pages
edit_other_article_pages delete_other_article_pages
read_private_faq_pages edit_private_faq_pages
delete_private_faq_pages read_other_faq_pages
edit_other_faq_pages delete_other_faq_pages
read_private_event_pages edit_private_event_pages
delete_private_event_pages read_other_event_pages
edit_other_event_pages delete_other_event_pages
approve_other_article_pages approve_private_article_pages
approve_other_cms_pages approve_private_cms_pages
approve_other_faq_pages approve_private_faq_pages
approve_other_event_pages approve_private_event_pages
read_private_cms_nodes read_other_cms_nodes
)
@sys_user = SS::User.where(email: "<EMAIL>").first
if @sys_user
@sys_user.add_to_set group_ids: g1_00.id
@sys_user.uid = "sys"
@sys_user.save!
@cms_user = Cms::User.find @sys_user.id
@cms_user.add_to_set cms_role_ids: role1.id
end
## -------------------------------------
puts "# users"
def save_user(data)
puts data[:name]
data[:in_password] = data[:password]
data.delete(:password)
group_ids = data[:group_ids]
data.delete(:group_ids)
cms_role_ids = data[:cms_role_ids]
data.delete(:cms_role_ids)
cond = { email: data[:email] }
item = SS::User.find_or_create_by cond
item.update data
item.add_to_set group_ids: group_ids
cms_user = Cms::User.find item.id
cms_user.add_to_set cms_role_ids: cms_role_ids
item
end
@admin = save_user name: "サイト管理者", email: "<EMAIL>", password: "pass",
group_ids: [g1_11.id], cms_role_ids: [role1.id], uid: "admin"
@user1 = save_user name: "一般ユーザー1", email: "<EMAIL>", password: "<PASSWORD>",
group_ids: [g1_11.id, g1_21.id], cms_role_ids: [role2.id], uid: "user1"
@user2 = save_user name: "一般ユーザー2", email: "<EMAIL>", password: "<PASSWORD>",
group_ids: [g1_22.id], cms_role_ids: [role2.id], uid: "user2"
## -------------------------------------
puts "# workflow"
def save_workflow_route(data)
puts data[:name]
item = Workflow::Route.new
item.attributes = data
raise item.errors.full_messages.to_s unless item.save
item
end
approvers = Workflow::Extensions::Route::Approvers.new(
[ { level: 1, user_id: @user1.id }, { level: 2, user_id: @admin.id } ]
)
required_counts = Workflow::Extensions::Route::RequiredCounts.new(
[ false, false, false, false, false ]
)
save_workflow_route name: "多段承認", group_ids: [g1_00.id],
approvers: approvers, required_counts: required_counts
## -------------------------------------
puts "# nodes"
def save_node(data)
puts data[:name]
klass = data[:route].sub("/", "/node/").singularize.camelize.constantize
cond = { site_id: @site._id, filename: data[:filename] }
item = klass.unscoped.find_or_create_by cond
item.update data
item.add_to_set group_ids: @admin.group_ids
item.add_to_set group_ids: @user1.group_ids
item.add_to_set group_ids: @user2.group_ids
item.update
end
save_node route: "article/page", filename: "docs", name: "記事", shortcut: "show"
|
shirasagi/opendata
|
spec/models/article/page_spec.rb
|
<reponame>shirasagi/opendata
require 'spec_helper'
describe Article::Page, dbscope: :example do
# subject(:model) { Article::Page }
# subject(:factory) { :article_page }
#
# it_behaves_like "mongoid#save"
# it_behaves_like "mongoid#find"
describe "#attributes" do
subject(:item) { create :article_page }
it { expect(item.becomes_with_route).not_to eq nil }
it { expect(item.dirname).not_to eq nil }
it { expect(item.basename).not_to eq nil }
it { expect(item.path).not_to eq nil }
it { expect(item.url).not_to eq nil }
it { expect(item.full_url).not_to eq nil }
it { expect(item.parent).to eq nil }
end
describe "shirasagi-442" do
subject(:item) { create :article_page, html: " <p>あ。→い</p>\r\n " }
its(:summary) { is_expected.to eq "あ。→い" }
end
end
|
shirasagi/opendata
|
lib/voice/converter.rb
|
<reponame>shirasagi/opendata
module Voice::Converter
class << self
public
def convert(site_id, html, output)
texts = Voice::Scraper::DEFAULT_INSTANCE.extract_text html
type = SS.config.voice.type
config = SS.config.voice[type]
tts = Voice::TextToSpeechFactory.create(type, config)
Dir.mktmpdir do |tmpdir|
wav_file = ::File.join(tmpdir, ::Dir::Tmpname.make_tmpname(["voice", ".wav"], nil))
tts.build(site_id, texts, wav_file)
mp3_file = ::File.join(tmpdir, ::Dir::Tmpname.make_tmpname(["voice", ".mp3"], nil))
Voice::WavToMp3.new.convert(wav_file, mp3_file)
Fs.binwrite(output, IO.binread(mp3_file))
true
end
end
end
end
|
shirasagi/opendata
|
app/controllers/cms/contents_controller.rb
|
<filename>app/controllers/cms/contents_controller.rb
class Cms::ContentsController < ApplicationController
include Cms::BaseFilter
navi_view "cms/main/navi"
private
def set_crumbs
@crumbs << [:"cms.content", action: :index]
end
public
def index
@model = Cms::Node
self.menu_view_file = nil
@mod = params[:mod]
cond = {}
cond[:route] = /^#{Regexp.escape(@mod)}\// if @mod.present?
@items = Cms::Node.site(@cur_site).
allow(:read, @cur_user).
where(cond).
where(shortcut: :show).
order_by(filename: 1).
page(params[:page]).per(100)
@notices = Cms::Notice.site(@cur_site).public.target_to(@cur_user).order_by(updated: -1)
end
def public_notice
@model = Cms::Notice
self.menu_view_file = "public_notice_menu"
@item = Cms::Notice.site(@cur_site).public.target_to(@cur_user).find(params[:notice])
end
end
|
shirasagi/opendata
|
config/routes/chorg/routes.rb
|
SS::Application.routes.draw do
# Chorg::Initializer
concern :deletion do
get :delete, on: :member
end
namespace("chorg_results", path: ".:site/chorgs/revisions/:rid", module: "chorg", id: /\w+/) do
resources :results, only: [:index, :show]
end
namespace("chorg_revisions", path: ".:site/chorgs", module: "chorg") do
resources :revisions, concerns: :deletion
end
namespace("chorg_changesets", path: ".:site/chorgs/revision:rid/:type", module: "chorg", rid: /\w+/, type: /\w+/) do
resources :changesets, concerns: :deletion
end
namespace("chorg_run", path: ".:site/chorgs/revision:rid/:type", module: "chorg", rid: /\w+/, type: /\w+/) do
get "confirmation" => "run#confirmation"
post "run" => "run#run"
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.