Как сделать опрос с помощью AppleScript

Традиционно каждый человек получает только один голос. Я хотел бы сделать то же самое с голосованием.

У меня есть куча учетных записей на моем Mac OS X на работе. Мы голосуем за избрание кого-то нашим новым главой отдела (нет, я не скажу кого), чтобы посмотреть, соответствует ли он требованиям для этой работы. Я решил написать небольшой скрипт, который сделает всю работу за нас. Однако я не могу сделать одну вещь: убедиться, что пользователь может голосовать только один раз. Мой скрипт ниже (очевидно, он не скомпилируется):

if the current user has never voted then --pseudo-code
    set the rating_results to (choose from list {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} with prompt "Please rate (anonymous) based on your observations. BE HONEST!")
    email_results(rating_results)
else
    display dialog "You already rated (anonymous)!"
end if

Я знаю, вы спросите: «Что я уже пробовал?» так я вам скажу. Пробовал get the current user, безрезультатно. Я также пробовал do shell script "echo $USER", что сработало, но я все еще знаю, как проверить, проголосовал ли пользователь.

Я предполагаю, что заголовок вопроса должен быть «Как я могу проверить, проголосовал ли пользователь?».

Спасибо большое,

Билл


person Bill    schedule 13.08.2011    source источник
comment
Введите все имена в текстовом документе. Распечатайте столько экземпляров, сколько избирателей, и раздайте каждому избирателю по экземпляру. Попросите их поставить галочку рядом с именем человека, которого они хотят избрать, сложить лист бумаги и положить его в картонную коробку. Когда все проголосовали, подсчитайте бюллетени. Избирается человек с наибольшим количеством галочек.   -  person Dour High Arch    schedule 13.08.2011
comment
Dour High, абсолютно блестящий. +1 за смех.   -  person BRampersad    schedule 13.08.2011


Ответы (1)


На вашем месте я бы сделал базу данных в приложении Database Events под названием "Избиратели". При запуске сценария проверьте наличие записи, имя которой совпадает с именем текущего пользователя. Если запись существует, пользователь проголосовал. Точно так же, если запись не существует, пользователь не проголосовал. В переводе на код этот абзац гласит:

set user_has_voted to false --inital value

tell application "Database Events"
    try
        get database "Voters"
        open database POSIX path of (path to documents folder) & "/Databases/Voters.dbev"
    on error
        make new database with properties {name:"Voters"}
        save
    end try
end tell
set the current_user to the long user name of (system info)
tell application "Database Events"
    tell database "Voters"
        try
            get record current_user
            --No error, the user has voted
            set user_has_voted to true
        on error
            make new record with properties {name:current_user}
            set user_has_voted to false
        end try
    end tell
    close database "Voters" saving yes
end tell

if user_has_voted then
    ...
else
    vote()
end if

Это более безопасно, чем использование property, поскольку позволяет определить, голосовал ли один и тот же пользователь в течение какого-либо периода времени.

ОБНОВЛЕНИЕ: Согласно комментарию @regulus6633, я добавил подпрограмму (которую вы можете поместить в конец предыдущего скрипта) и еще один скрипт, который поможет вам в работе. Подпрограмма сохраняет голоса в базе данных, а сценарий, следующий за подпрограммой, извлекает информацию из базы данных.

on vote()
    set the rating_results to (choose from list {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} with prompt "Please rate (somebody) based on your observations. BE HONEST!")
    if the rating_results is false then error number -128
    tell application "Database Events"
        try
            get database "Votes"
            open database POSIX path of (path to documents folder) & "/Databases/Votes.dbev"
        on error
            make new database with properties {name:"Votes"}
            save
        end try
        try
            get record "Vote Frequency" of database "Votes"
        on error
            tell database "Votes" to make new record with properties {name:"Vote Frequency"}
        end try
        tell database "Votes"
            tell record "Vote Frequency"
                if exists field rating_results then
                    set the value of field rating_results to the value of field rating_results & the rating_results
                else
                    tell (make new field with properties {name:rating_results, value:{}}) to set the end of the value of it to the rating_results
                end if
            end tell
        end tell
        close database "Votes" saving yes
    end tell
end vote

Вот как можно получить информацию о голосовании из базы данных Votes.

tell application "Database Events"
    try
        get database "Votes"
        open database POSIX path of (path to documents folder) & "/Databases/Votes"
    on error
        my nobody_voted_yet() --Database Events doesn't allow any user interaction, so we have to use a subroutine to display information to the user
    end try
    set the votes to {}
    set the vote_total to 0
    tell database "Votes"
        tell record "Vote Frequency"
            repeat with i from 1 to the count of fields
                repeat with this_vote in the value of field i
                    set the end of votes to this_vote
                    set the vote_total to the vote_total + this_vote
                end repeat
            end repeat
        end tell
    end tell
    close database "Votes" saving yes --It is always a good idea to save the database, even if you're just retrieving values. This reduces the risk of the values changing themselves.
    my average_votes(votes, vote_total)
end tell

on nobody_voted_yet()
    display dialog "Nobody voted yet! You can't retrieve information that doesn't exist!" buttons{"Cancel"} default button 1
end nobody_voted_yet

on average_votes(vote_length, vote_total)
    set the voting_result to (the vote_total / (length of the vote_length))
    display dialog "The average rating for (somebody) is: " & (round the voting_result as string)
end average_votes
person fireshadow52    schedule 13.08.2011
comment
Мне нравится эта идея базы данных. Это легко и эффективно. Хотя я бы продлил. Почему бы не сохранить голосование в базе данных? Тогда вам не нужно будет получать электронное письмо о голосовании. Вы можете использовать второй скрипт для получения голосов из базы данных. Второй скрипт суммирует их для вас и делит на общее количество записей в базе данных, чтобы получить средний рейтинг. - person regulus6633; 13.08.2011
comment
@regulus6633 regulus6633 Я обновил ответ, чтобы отразить то, что вы сказали :) - person fireshadow52; 13.08.2011
comment
Очень хороший fireshadow52, мне нравится! - person regulus6633; 14.08.2011
comment
@regulus6633 Держу пари, ты бы снова проголосовал за это, если бы мог :P - person fireshadow52; 14.08.2011