Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 85

0
votes
answers
17 views
+10

How to write to file in Ruby?

I need to read the data out of database and then save it in a text file.

How can I do that in Ruby? Is there any file management system in Ruby?

0
votes
answers
20 views
+10

無法在Rails中使用ActiveStorage創建文件字段

4

我正嘗試在Rails 5.2中使用Active Storage。我發現,我應該在遷移file類型創建領域,但我有一個錯誤:無法在Rails中使用ActiveStorage創建文件字段

$ rdm 
Running via Spring preloader in process 40193 
== 20171217191942 CreateDishes: migrating 
===================================== 
-- create_table(:dishes) 
rake aborted! 
StandardError: An error has occurred, this and all later migrations canceled: 

undefined method `file' for #<ActiveRecord::ConnectionAdapters::PostgreSQL::TableDefinition:0x00007fd56e297750> 
/Users/alder/Projects/_apps/service_exchange/rails-backend/db/migrate/20171217191942_create_dishes.rb:6:in `block in change' 
/Users/alder/Projects/_apps/service_exchange/rails-backend/db/migrate/20171217191942_create_dishes.rb:3:in `change' 
-e:1:in `<main>' 

遷移:

class CreateDishes < ActiveRecord::Migration[5.2] 
    def change 
    create_table :dishes do |t| 
     t.string :name, index: true 
     t.string :description 
     t.file :image 

     t.timestamps 
    end 
    end 
end 

我試圖創建字符串字段,但它不工作。

找不到關於在official docs

我有主動式存儲遷移和我通過什麼好的

+1

我很確定在rails遷移中沒有這樣的數據類型'文件',請嘗試使用f.string –

+1

檢查此博客:https://rubyinrails.com/2017/07/21/rails-introduces-active- storage-for-file-uploads/ –

+0

所以,是的,我使用了那個鏈接。如果你創建字符串字段,它會在稍後顯示類型不匹配。 – zishe

沙发
0
10

相反,你需要在自己的遷移創建一個專用領域的一個文件(t.file :image)主動存儲使用兩個表,你setuprails active_storage:install。 當您建立storage.yml你應該能夠使用

has_one_attached :image 
Dishes模型中

,而無需創建image列。

+0

我認爲我可能不應該爲圖像創建任何字段,稍後我會檢查它,但我猜這是正確的答案。 – zishe

+0

是的,你是對的,謝謝你的回答! – zishe

板凳
0
4

您可以檢查這個問題,因爲(ActiveRecord field type)沒有任何類型的像file如果你需要上傳你可以用string類型創建像t.string

0
votes
answers
6 views
+10

顯示只在欄中的字符串的前x個字符

-1

我有一個輸出爲「2017-11-17T06:06:29.000 + 0000」我只想在「T」之前的日期部分如何使用紅寶石分割它在軌道上?顯示只在欄中的字符串的前x個字符

+0

這個答案可以很容易地搜索到 – AntonTkachov

沙发
0
0

"2017-11-17T06:06:29.000+0000".first(10)更容易理解
"2017-11-17T06:06:29.000+0000".split('T').first更通用的方式,從時間分割日期

PS:我已經打上你節制的問題,因爲這個問題是一個基本的,可以很容易地發現在手冊/文檔/谷歌。

板凳
0
1

您可以使用strftime打印出所需的格式。 使用<%=date.strftime.("%F") %>打印您所需的日期格式。 以下是需要的參考文件:https://apidock.com/ruby/DateTime/strftime

0
votes
answers
25 views
+10

產品和類別關係

0

試圖在我的應用程序中具有以下關係。產品和類別關係

產品可以屬於許多類別,子類別和子類別。

目前的設計:

Product: 
    has_many :categorizations, dependent: :destroy 
    has_many :categories, through: :categorizations 
    has_many :sub_categories, through: :categorizations 
    has_many :sub_sub_categories, through: :categorizations 

Category: 
    has_many :categorizations 
    has_many :products, through: :categorizations 
    has_many :sub_categories, class_name: 'Category', foreign_key: 'parent_id' 
    belongs_to :parent_category, class_name: 'Category', foreign_key: 'parent_id' 

Categorization: 
    belongs_to :category 
    belongs_to :sub_category, class_name: 'Category', foreign_key: 'sub_category_id' 
    belongs_to :sub_sub_category, class_name: 'Category', foreign_key: 'sub_sub_category_id' 
    belongs_to :product 

產品特定類別的可以被列爲category.products

如何訪問特定產品sub_categorysub_sub_category

我應該做些什麼?

沙发
0
0

將此線路has_many :sub_sub_categories, through: :sub_categories添加到Product型號。

## app/models/product.rb 
has_many :sub_categories 
has_many :categories, through: :sub_categories 
has_many :sub_sub_categories, through: :sub_categories 

如果我是你,我會設計這樣的:

Product: 
    has_many :categorizations 
    has_many :categories, through: :categorizations 

Categorization: 
    belongs_to :product 
    belongs_to :category 

Category: 
    belongs_to :parent, class_name: 'Category', optional: true 
    has_many :children, class_name: 'Category', foreign_key: :parent_id, dependent: :nullify 

    has_many :categorizations 
    has_many :products, through: :categorizations 

注:添加parent_idcategories

+0

謝謝。和上面的設計是罰款或使用自引用關係在'category'而不是'sub_category'更好? – rAzOr

+0

看看我編輯的答案@rAzOr – fongfan999

20
votes
answers
10 views
+10

Rubygems: How do I add platform-specific dependency?

I've a ruby gem that has different dependencies for each OS. I have to explicitly write all of them down:

On Mac OS X:

gem install livereload

on Linux:

gem install rb-inotify livereload

on Windows:

gem install eventmachine-win32 win32-changenotify win32-event livereload

Can I tweak a gemspec a bit so installation instructions would look like plain gem install livereload for every OS?

up vote 20 down vote accepted favorite
沙发
+200
+50

這裡概述執行此操作的正確方法由於gemspec是在打包時評估的,因此您需要在本機擴展中進行評估。不要擔心,它不是那麼可怕,因為它仍然只是Ruby代碼(不編譯C或任何東西)。

我們目前正在將這種方法用於OpenShift的一些客戶端工具(源代碼)然後在你的gemspec / Rakefile中,你可以添加一個擴展名,而不是添加依賴項。請注意,需要為此命名文件ext/mkrf_conf.rb才能生效。

0
votes
answers
22 views
+10

如何判斷在正則表達式中匹配之間是否有三個或更多的字符?

1

我正在使用Ruby 2.1。我有這樣的邏輯,看起來連續字符串對在一個更大的字符串如何判斷在正則表達式中匹配之間是否有三個或更多的字符?

results = line.scan(/((S+?).*?(S+?))/) 

我的問題是,我該如何遍歷結果列表中,並打印出是否有兩個字符串之間的三個或更多字符?舉例來說,如果我的字符串是

"abc  def" 

以上會產生

[["abc  def", "abc", "def"]] 

,我想知道是否有「ABC」和之間的三個或更多字符「高清」。

+1

你參考(這是符合你的正則表達式),但你的榜樣「兩個字符串之間的三個或更多字符」只包含兩個字符串之間的空格(即一個特定字符)。這是令人困惑的。 –

+0

我正在使用與我的表達式匹配的示例。我在我的問題b/c中使用了「characters」而不是「spaces」,我的正則表達式可能會比空格匹配更多。請讓我知道我能做些什麼來使問題更清楚。感謝卡里。 – Dave

+0

@Dave除了空格還有什麼可能? – wp78de

沙发
0
3

使用量詞的空間其間:((S+?)s{3,}(S+?))

而且,實際上並不需要內boundries: ((S+?)s{3,}(S+?))

+0

你改變我的正則表達式。我不想排除它們之間少於3個字符的對,我只是想確定當我遍歷結果集時哪些對是那些對。 – Dave

+0

戴夫,沒有必要引用你的「結果集」來產生你想要的結果。 wp78de正在提取兩個匹配之間有3個或更多空格的字符串(這些字符將位於結果集中),與您的示例一致。如果它們之間應該是「3或更多*字符*」,則用'。{3,}'替換' s {3,}'。 –

+0

@Dave如果你真的想要走這條路線,你可以使用這樣一個更復雜的模式,如果它們之間有3個或更多的空格,那麼它的價值在2美元:[' b(?:( w +?) :?( S {3,...})| b * b)( W +)) B'](https://regex101.com/r/v3oG9M/3) – wp78de

板凳
0
0

一個簡單的方法來檢查,這是通過運行一個獨立的正則表達式:

results.select!{|x|p x[/S+?(.*?)S+?/,1].size} 

將打印每一堆的大小。

另一種方法是把拍攝組的大小和減去它們:

results = [] 
line.scan(/((S+?).*?(S+?))/) do |s, group1, group2| 
    results << $~ if s.size - group1.size - group2.size >= 3 
end 
4
votes
answers
17 views
+10

If string is empty then return some default value

Often I need to check if some value is blank and write that "No data present" like that:

@user.address.blank? ? "We don't know user's address" : @user.address

And when we have got about 20-30 fields that we need to process this way it becomes ugly.

What I've made is extended String class with or method

class String
  def or(what)
    self.strip.blank? ? what : self
  end
end

@user.address.or("We don't know user's address")

Now it is looking better. But it is still raw and rough

How it would be better to solve my problem. Maybe it would be better to extend ActiveSupport class or use helper method or mixins or anything else. What ruby idealogy, your experience and best practices can tell to me.

沙发
+20

您的方法可能會產生一些不必要的副作用,因為始終會評估備用(默認)值,即使該字符串不為空。

例如< / p>

  @ user.address.or User.make_a_long_and_painful_SQL_query_here   

即使地址不為空,也可以進行額外的工作。也許你可以更新一點(抱歉混淆一行,試圖保持簡短):

  class String def或what =“”self.strip.empty?block_given?yield:what:self end end @ user.address.or“我們不知道用戶的地址”@ user.address.or {User.make_a_long_and_painful_SQL_query_here}  
     
			
        
板凳
+20

最好擴展ActiveRecord或單個模型而不是String。

在您的視圖中,您可能更喜歡更明確的模式,如

  @ user.attr_or_default :地址,“我們不知道用戶的地址” 
     
			
        
地板
0

Ruby:

 除非my_str.empty?然後my_str else'默認'結束  

RoR:

 除非my_str.blank?然後my_str其他'默認'結束 
     
			
        
65
votes
answers
30 views
+10

How to create a new Ruby gem?

To create a new Ruby gem, should I use Jeweler or should I use Bundler's built-in gem skeleton to create a base gem? What are the differences that matter?

up vote 52 down vote accepted favorite
沙发
+520
+50

使用Bundler

從命令行:

bundle gem your_new_gem

這將創建一個目錄your_new_gem,只調用一組基本文件和目錄結構,這些目錄現在被認為是最佳實踐。它快速,簡單,是一個很好的起點。

+70

創建寶石並不困難,我建議嘗試從頭開始構建寶石,不需要任何工具。在您知道所涉及的內容(創建gemspec,構建並將其推送到rubygems.org)之後,您可以使用工具來加速該過程。我的猜測是你不會因為製作寶石幾乎不是麻煩。

Good point. It is better to understand how to do it from scratch before you use a generator. This will make it alot easier to debug any problems that arise if you decide to use Jeweler. I do think that Jeweler makes it alot easier to create a gem and it forces you to do things like creating a description, versioning, etc.. why would you create it from scratch (after you do it once to learn it), when you can use a Jeweler and speed the process? Waste of time in my opinion, and less prone to errors. – johnmcaliley Dec 5 '10 at 19:35

I appreciate the discussion. – Daniel Kehoe Dec 6 '10 at 3:02

sorry I'm late: What jeweler creates isn't easier, it just moves the stuff to the Rakefile. A gemspec is only about 10 lines. I like the stuff bundler generates though. Sensible and minimal. – iain Dec 9 '10 at 21:57

Learning to write a gem from scratch instead of using a generator is like writing a web framework from scratch without using rails new. I see your point about creating one from scratch, but for someone new to creating gems (or anything for that matter), sometimes it's easier to learn by example. When you see what the generator builds, you can learn what each piece does and why it is important to the structure. Once you understand how it works, then you can write one from scratch. – Andrew Jul 16 '11 at 5:54

In that case, I would go for the generator provided by bundler gem. – iain Jul 17 '11 at 11:34

+30

我會和珠寶商一起去。Bundler骨架只會為您提供基礎知識。Jeweler有很多選擇可以使用和許多有用的rake任務進行版本控制,推送到github,創建gemspec,構建和安裝。

如果您正在使用Rails 3引擎,我有一個Jeweler fork(絕對是正在進行中的工作),它將生成應用程序skelaton並包含引擎文件。你只需要運行jeweler命令--rails3-engine作為選項。如果你有興趣,這是fork:https
//github.com/johnmcaliley/jeweler

Jeweler is no longer kept up-to-date as much as Bundler, as the author confesses that most people now use Bundler instead: github.com/technicalpickles/jeweler/issues/232 – Jon Cairns Feb 15 '13 at 8:58

I agree. I no longer use jeweler. It is probably better to start from scratch your first time, so you understand how the gemspec works. – johnmcaliley Feb 15 '13 at 14:39

+10

這是一個值得關注的替代品:礦石

Bundler為ruby gems提供了一個模板,而ore有多個內置模板,還有創建自己的模板的能力。它還支持Git,SVN(urgh)和Mercurial。

+10

我建議使用內置的bundler命令。

bundle gem your_gem_name

創建gem時應遵循一些規則。例如命名約定和版本控制規則。我最近寫了一篇關於在netguru博客中創建寶石的文章。我想你會在那裡找到你需要的東西。

https://netguru.co/blog/posts/creating-a-gem-a-step-by-step-tutorial

希望這可以幫助。

It is a duplicate of stackoverflow.com/a/11674455/4130619 (top answer), with spammy link as the only addition. – Mateusz Konieczny Oct 15 '18 at 16:31

+10

您也可以在RubyMine中構建gem。文件>新項目>新寶石。就這麼簡單。但我想對這種方法做一些注意事項:

對於調試,RubyMine將使用Fast Debugger gem,ruby-debug-ide。我知道現在大多數人都在使用Pry和Byebug,但是ruby-debug-ide是一個將ruby-debug粘貼到Eclipse(RDT),NetBeans和RubyMine等IDE上的接口。

在運行>編輯配置> +> Ruby下,我根據以下文檔添加了一個新的調試配置:https//www.jetbrains.com/help/ruby/run-debug-configuration-gem-command.html#1

在Configuration下,在'Ruby Script'下,我在lib下添加了ruby gem文件的路徑:lib / my_gem.rb在Configuration下,在'Ruby SDK'下,我指定了一個我正在使用的RVM gemset。在Bundler部分下,我檢查'在bundler上下文中運行腳本'。這將使用bundle exec,它將讀取項目根目錄中Gemfile中的依賴項。現在對於gems,Gemfile包含一個方法調用“gemspec”,該方法又調用my_gem.gemspec中依賴項中的依賴項。在那裡,我有依賴傳遞給Gem :: Specification.new塊:

  spec.add_development_dependency "bundler", "~> 1.7"
  spec.add_development_dependency "rake", "~> 10.0"
0
votes
answers
33 views
+10

Gravatar在中國被封鎖,需要一個解決方法

1

我正在開發一個Ruby on Rails應用程序。Gravatar在中國被封鎖,需要一個解決方法

Gravatar在中國受阻,我們有大量的用戶。這意味着如果您從應用程序的Gravatar網站中提取,您的網站將會崩潰/無法加載中國任何人。

所以,我有兩個選擇:

  1. 上傳所有gravatars到S3與工人併爲他們自己
  2. 找出一個解決辦法

解決方法1是使用CDN喜歡的CloudFlare我可以用來服務Gravatars。如果存在即插即用的東西,那將會很棒,它也會提高性能。

解決方法#2將根據中國用戶的IP地址爲中國境內的任何人提取中國鏡像鏡像。

解決方法#3是使用Gravatar Ultimate gem(使用ActiveSupport :: Cache :: SynchronizedMemoryStore.new(https://github.com/sinisterchipmunk/gravatar))緩存圖像。我不確定這是否可以爲成千上萬的日常用戶擴展。

解決方法#4將以某種方式在瀏覽器中檢測到Gravatar發生的故障,並且它無法顯示默認(非基於圖像的)頭像。如果在第一次嘗試之後爲所有的頭像做過這些事情,或者在後續的嘗試中記住並記住它,那將會很棒。

也許第四個是最簡單/最強大的,但我不知道該怎麼做。對於gravatars,我一直用這個簡單的輔助方法:

def gravatar_url(user) 
    gravatar_id = Digest::MD5.hexdigest(user.email.downcase) 
    "http://gravatar.com/avatar/#{gravatar_id}.png?d=identicon&s=150" 
end 
+0

你的意思是說你有很多用戶,不是'from'gravatar,而是''使用'* gravatar作爲他們的個人資料圖片? – AntonTkachov

+0

不,我的意思是任何基於中國的用戶,如果您嘗試鏈接到gravatar.com上託管的圖片,您的應用程序將無法加載,甚至可能會崩潰。 –

+1

您可以嘗試加載圖像服務器端,然後base64編碼數據並呈現圖像內聯,應該繞過任何過濾器,如:https://stackoverflow.com/questions/22717251/how-cani-i-顯示PNG-數據即一個圖像-內部功能於所述瀏覽器 – DivXZero

沙发
0
0

有一個在https://cdn.v2ex.com/gravatar/5e801ed65b6f99fcad45fc7e61a5ffde

這裏鏡子一般也作爲一個經驗法則,在GFW是HTTPS交通道口那麼寬容,所以如果你在gravatar.com上使用HTTP,可能會有一些改進

0
votes
answers
20 views
+10

Installing Cocoapods on OS X El Capitan error

First of all. I updated to El Capitan because of iOS 9.3 and it's support only in xCode 7.3.

After update I discovered that pod command isn't working. I executed:

sudo gem install cocoapods
ERROR:  Error installing cocoapods:
    activesupport requires Ruby version >= 2.2.2.

So my problem is that I can't install cocoapods. I don't know nothing about gems and ruby stuff. Does somebody know how to handle this?

I had second OS X with El Capitan 10.11.4 and everything went ok so I don't know from where this issue is coming from.

UPDATE: 5 April 2016

I executed several commands on terminal for more info:

Kapucha:~ kapucha$ which ruby
/usr/bin/ruby
Kapucha:~ kapucha$ which gem
/usr/bin/gem
Kapucha:~ kapucha$ which brew
/usr/local/bin/brew
Kapucha:~ kapucha$ which rvm
/Users/kapucha/.rvm/bin/rvm

Versions:

Kapucha:~ kapucha$ ruby --version
ruby 2.0.0p648 (2015-12-16 revision 53162) [universal.x86_64-darwin15]
Kapucha:~ kapucha$ gem --version
2.2.2
Kapucha:~ kapucha$ brew --version
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/fileutils.rb:245:in `mkdir': Permission denied - /Library/Ruby/Gems/2.0.0/extensions/universal-darwin-15 (Errno::EACCES)
Kapucha:~ kapucha$ rvm --version
rvm 1.27.0 (latest) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]

.bash_profile file and .profile

Kapucha:~ kapucha$ cat .bash_profile
export JAVA_HOME=$(/usr/libexec/java_home)
. ~/.bashrc
source ~/.profile

Kapucha:~ kapucha$ cat .profile
export PATH="$PATH:$HOME/.rvm/bin" # Add RVM to PATH for scripting
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*

rvm list and rvm info

Kapucha:local kapucha$ rvm list

rvm rubies


# No rvm rubies installed yet. Try 'rvm help install'.

Kapucha:local kapucha$ rvm info

system:

  system:
    uname:       "Darwin Kapucha.local 15.4.0 Darwin Kernel Version 15.4.0: Fri Feb 26 22:08:05 PST 2016; root:xnu-3248.40.184~3/RELEASE_X86_64 x86_64"
    system:      "osx/10.11/x86_64"
    bash:        "/bin/bash => GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin15)"
    zsh:         "/bin/zsh => zsh 5.0.8 (x86_64-apple-darwin15.0)"

  rvm:
    version:      "rvm 1.27.0 (latest) by Wayne E. Seguin <wayneeseguin@gmail.com>, Michal Papis <mpapis@gmail.com> [https://rvm.io/]"
    updated:      "18 hours 23 minutes 25 seconds ago"
    path:         "/Users/kapucha/.rvm"

  homes:
    gem:          "not set"
    ruby:         "not set"

  binaries:
    ruby:         "/usr/bin/ruby"
    irb:          "/usr/bin/irb"
    gem:          "/usr/bin/gem"
    rake:         "/usr/bin/rake"

  environment:
    PATH:         "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/filipkotwicki/dev/tools/android-sdk-macosx/platform-tools:~/bin:/opt/X11/bin:/usr/local/git/bin:/Users/kapucha/.rvm/bin:/Users/kapucha/.rvm/bin"
    GEM_HOME:     ""
    GEM_PATH:     ""
    MY_RUBY_HOME: ""
    IRBRC:        ""
    RUBYOPT:      ""
    gemset:       ""

When I'm triying to install Ruby with rvm

Kapucha:local kapucha$ rvm install 2.2.2
Searching for binary rubies, this might take some time.
Found remote file https://rvm_io.global.ssl.fastly.net/binaries/osx/10.11/x86_64/ruby-2.2.2.tar.bz2
Checking requirements for osx.
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/fileutils.rb:245:in `mkdir': Permission denied - /Library/Ruby/Gems/2.0.0/extensions/universal-darwin-15 (Errno::EACCES)
...
ERROR: '/bin' is not writable - it is required for Homebrew, try 'brew doctor' to fix it!
Requirements installation failed with status: 1.

Tried brew doctor with the same result:

Kapucha:local kapucha$ brew doctor
/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/fileutils.rb:245:in `mkdir': Permission denied - /Library/Ruby/Gems/2.0.0/extensions/universal-darwin-15 (Errno::EACCES)
沙发
0

activesupportCocoapods 依賴的寶石需要Ruby版本大於2.2.2(見這裡)。

您使用的是哪個版本的Ruby(類型ruby --version)?也許您的第二個OS X系統正在使用系統Ruby版本(您可以通過鍵入來檢查它which ruby)。

可能你需要安裝更新版本的Ruby(例如2.2.3)。我建議使用RVM在您的機器上安裝和管理Ruby版本。

No problem. Glad that I helped. :) – Aleksander Grzyb Apr 5 '16 at 12:02

板凳
0

使用以下命令安裝homebrew

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

然後安裝cocoapods而不使用sudo

gem install cocoapods

地板
0

請從安裝最新版本的Ruby和RVM(Ruby的版本管理器)的這個環節。

然後運行“ sudo install cocoapods

4楼
0

El Capitan 10.11.3

1)$ sudo gem install activesupport -v 4.2.6

2)$ sudo gem install -n / usr / local / bin cocoapods