如何让这段代码变得更好? (sinatra + 数据映射器)

发布于 2024-12-20 02:06:55 字数 771 浏览 2 评论 0原文

我对此很陌生,我正在使用 datamapper 和 sinatra 来构建一个基本的应用程序。我有一个设置页面,其中包含一些用于几种不同设置的文本输入。

查看此页面时,应该从数据库中提取信息并填充输入框(如果有)。

对于我的设置类,我有 :name 和 :value

截至目前,我的代码正在运行,如果名称尚不存在,则允许创建设置,否则会更新它。

Setting.first_or_create(:name => "seed").update(:name => "seed", :value => params[:seed])

3个问题:

  1. 如果输入为空(显然在第一次之后),它会用“”覆盖它

  2. 如何缩短这段代码?在“真正的”Ruby 程序中,我应该定义一个方法,这样就没有那么多冗余代码吗?我有 5 个设置,所以我觉得这行代码出现 5 次,只有几处不同,这有点糟糕。困难在于我将被迫将我所有的输入命名为我正在使用的确切哈希值。我不确定这是否是不好的做法,或者我是否应该明确地执行 5 次

  3. 为了“获取”数据来显示它,我有这个:

    @seed = Setting.get(:name => "seed")
    

    这显然不起作用...我需要的是获取 params[:value] WHERE :name => “种子”和使用 <%= @seed(???) %>将其打印出来。我不知道如何做到这一点

I'm new to this, and I'm using datamapper and sinatra to build a basic app. I have a settings page with a few text inputs for several different settings.

This page, when viewed, should pull the information from the database and populate the input boxes if they're there.

For my Setting class I have :name and :value

As of right now, I have the code working which allows a setting to be created if the name doesnt already exist, and it updates it otherwise.

Setting.first_or_create(:name => "seed").update(:name => "seed", :value => params[:seed])

3 problems:

  1. if the input is blank (after the first time obviously), it overwrites it with ""

  2. How can I shorten this code down? In a 'real' ruby program, should i define a method so theres not so much redundant code? I have 5 settings so i feel having that line of code 5 times with only a few things different is kind of poor. The difficulty is that I would be forced to name="" all my inputs the exact hash that i'm using. Im not sure if thats poor practice or not, or whether I should just do it all explicitly 5 times

  3. In order to 'get' the data to display it i have this:

    @seed  = Setting.get(:name => "seed")
    

    That obviously doesn't work... what I need is to get params[:value] WHERE :name => "seed" and the use <%= @seed(???) %> to print it out. im not sure how to do this

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南笙 2024-12-27 02:06:55
@seed = Setting.first_or_create(:name => "seed") # fetch and store
# update only if there was one
@seed.update(:name => "seed", :value => params[:seed]) if params[:seed].present?

<!-- show the value in the page -->
<%= @seed.value %>
@seed = Setting.first_or_create(:name => "seed") # fetch and store
# update only if there was one
@seed.update(:name => "seed", :value => params[:seed]) if params[:seed].present?

<!-- show the value in the page -->
<%= @seed.value %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文